I have a variable in a shell script in which I'd like to format the data. The variable stores new data during every iteration of a loop. Each time the new data is stored, I'd like to insert a new line character. Here is how I'm trying to store the data into the variable.
VARIABLE="$VARIABLE '\n' SomeData"
Unfortunately, the output includes the literal '\n'
Any help would be appreciative.
The most used newline character If you don't want to use echo repeatedly to create new lines in your shell script, then you can use the \n character. The \n is a newline character for Unix-based systems; it helps to push the commands that come after it onto a new line. An example is below.
Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.
use ctrl-v ctrl-m key combos twice to insert two newline control character in the terminal. Ctrl-v lets you insert control characters into the terminal. You could use the enter or return key instead of the ctrol-m if you like. It inserts the same thing.
Try $'\n'
:
VAR=a VAR="$VAR"$'\n'b echo "$VAR"
gives me
a b
A common technique is:
nl=' ' VARIABLE="PreviousData" VARIABLE="$VARIABLE${nl}SomeData" echo "$VARIABLE" PreviousData SomeData
Also common, to prevent inadvertently having your string start with a newline:
VARIABLE="$VARIABLE${VARIABLE:+$nl}SomeData"
(The expression ${VARIABLE:+$nl}
will expand to a newline if and only if VARIABLE is set and non-empty.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With