Using ANSI C quoting:
var="$var"$'\n'"in a box"
You could put the $'\n'
in a variable:
newline=$'\n'
var="$var${newline}in a box"
By the way, in this case, it's better to use the concatenation operator:
var+="${newline}in a box"
If you don't like ANSI C quoting, you can use printf
with its -v
option:
printf -v var '%s\n%s' "$var" "in a box"
Then, to print the content of the variable var
, don't forget quotes!
echo "$var"
or, better yet,
printf '%s\n' "$var"
Remark. Don't use upper case variable names in Bash. It's terrible, and one day it will clash with an already existing variable!
You could also make a function to append a newline and a string to a variable using indirect expansion (have a look in the Shell Parameter Expansion section of the manual) as so:
append_with_newline() { printf -v "$1" '%s\n%s' "${!1}" "$2"; }
Then:
$ var="The "
$ var+="cat wears a mask"
$ append_with_newline var "in a box"
$ printf '%s\n' "$var"
The cat wears a mask
in a box
$ # There's no cheating. Look at the content of 'var':
$ declare -p var
declare -- var="The cat wears a mask
in a box"
Just for fun, here's a generalized version of the append_with_newline
function that takes n+1 arguments (n≥1) and that will concatenate them all (with exception of the first one being the name of a variable that will be expanded) using a newline as separator, and puts the answer in the variable, the name of which is given in the first argument:
concatenate_with_newlines() { local IFS=$'\n'; printf -v "$1" '%s\n%s' "${!1}" "${*:2}"; }
Look how well it works:
$ var="hello"
$ concatenate_with_newlines var "a gorilla" "a banana" "and foobar"
$ printf '%s\n' "$var"
hello
a gorilla
a banana
and foobar
$ # :)
It's a funny trickery with IFS
and "$*"
.