Missing new lines in Bash in passing function to variable [duplicate] - bash

This question already has answers here:
When to wrap quotes around a shell variable?
(5 answers)
Closed 1 year ago.
Why in this case doesnt generate new lines in Bash:
#!/bin/bash
function sample() {
local DATA=""
DATA="test1"$'\n'
DATA="${DATA}test2"$'\n'
echo ${DATA}
}
DATA=$(sample)
printf "%s" "${DATA}"

$DATA is expanded, and all whitespace (including newlines) are used for word-splitting, before echo ever runs. You should always quote parameters expansions.
sample() {
local DATA=""
DATA="test1"$'\n'
DATA="${DATA}test2"$'\n'
echo "${DATA}"
}

You must use the -e option of echo for it to interpret the \n character:
echo -e "${DATA}"

Related

How to replace `eval` when assigning variables in Bash [duplicate]

This question already has answers here:
Passing arguments by reference
(9 answers)
Closed 2 years ago.
I have a function myFunction() that shall take an integer variable from outside, print it and then increment it.
This works:
myFunction:
myFunction() {
local var="${1}"
eval "printf '%s\n' \$$var"
eval "$var=$(($var+1))"
}
But, I don't want to use eval in this as a user of this function might enter a wrong variable name that might then be executed. I would like to use something like printf -v as it would make the usage safer.
How can I do this?
You can (only?) do this without eval if you are happy enumerating all possible variable names.
myFunction () {
case $1 in
(frobme) printf '%s\n' $frobme; : $((++frobme));;
(zapme) printf '%s\n' $zapme; : $((++zapme));;
(*) printf 'invalid name: %s\n' "$1" >&2;;
esac
}

Value of var is not shown when concatenating $ and var --> $var [duplicate]

This question already has answers here:
How can I look up a variable by name with #!/bin/sh (POSIX sh)?
(4 answers)
Bash String concatenation and get content
(2 answers)
Closed 4 years ago.
I've got about a day of experience in bash as of now..
string () {
for (( i=0; i<${#1}; i++ ))
do
echo "$"${1:$i:1}""
done
}
string "hello"
This script returns "$h", "$e", "$l", "$l", "$o",
but I actually want it to return the contents of variables h, e, l, l and o.
How do I do that?
You need to use indirect parameter expansion:
for ((i=0; i<${#1}; i++)); do
t=${1:i:1}
echo "${!t}"
done
${!t} takes the value of $t, and treats that as the name of the parameter to expand.
A one-liner using eval to safely write a series of echos to output bash parameter transformation assignment statements, with GNU grep divvying up the input string:
h=foo o=bar
string() { eval $(printf 'echo ${%s#A};\n' $(grep -o . <<< "$#" )) ; }
string hello
Output, (blank lines represent the unset variables $e and $l):
h='foo'
o='bar'

How to write a multiline string to a file in Bash [duplicate]

This question already has answers here:
I just assigned a variable, but echo $variable shows something else
(7 answers)
Closed 6 years ago.
I want to rewrite a configuration file when asked from a bash script. Here is my code.
function quality {
echo $1 > ~/.livestreamerrc
echo ".livestreamer was modified!"
}
best="stream-types=hls
hls-segment-threads=4
default-stream=best
player=vlc --cache 5000"
read -p "Set quality: " INPUT
if [[ "$INPUT" == "!best" ]]; then
quality $best
fi
This code does the following to .livestreamer file though.
$cat ~/.livestreamerrc
stream-types=hls
Why?
Change it to
quality "$best" # double quotes to avoid word splitting
and then
echo "$1" > ~/.livestreamerrc
Note : Worth checking the [ shellcheck ] documentation.Also, fully uppercase variables like INPUT are reserved for the system.

How to remove leading whitespace from a string in Bash [duplicate]

This question already has answers here:
How to trim whitespace from a Bash variable?
(52 answers)
Closed 7 years ago.
For example, I have a string, " some string", and I want to put "some string" in another string variable. How do I do that?
My code:
function get_title() {
t1=$(get_type "$1")
t2="ACM Transactions"
t3="ELSEVIER"
t4="IEEE Transactions"
t5="MIT Press"
if [ "$t1"=="$t2" ];
then
title=$(less "$1" | head -1)
elif [ "$t1"=="$t5" ];
then
title=$(less "$1" | head -3)
fi
echo "$title"
}
As you can see the $title can return unwanted whitespace in front of text in center aligned texts. I want to prevent that.
A robust and straightforward approach is to use sed e.g.
$ sed 's/^[[:space:]]*//' <<< "$var"
If you are willing to turn on extended globbing (shopt -s extglob), then the following will remove initial whitespace from $var:
"${var##+([[:space:]])}"
Example:
var=$' \t abc \t ' echo "=${var##+([[:space:]])}="
=abc =

How to preserve trailing whitespace in bash function arguments? [duplicate]

This question already has answers here:
When to wrap quotes around a shell variable?
(5 answers)
Closed 3 years ago.
Consider the following bash script:
#!/bin/bash
function foo {
echo -n $1
echo $2
}
foo 'Testing... ' 'OK' # => Testing...OK
# Whitespace --^ ^
# Missing whitespace -----------------^
What happened to the trailing whitespace in the first argument? How can preserve it?
What happened to the trailing whitespace in the first argument?
The whitespace was included on the echo command line, but was discarded by the shell, the same as if you had typed:
echo -n Testing...
^
|----- there is a space here
How can preserve it?
Quote your variables:
function foo {
echo -n "$1"
echo "$2"
}

Resources