Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding newline characters to unix shell variables

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.

like image 295
James P. Avatar asked Feb 22 '12 21:02

James P.


People also ask

How do you add a new line character in Unix shell script?

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.

How do you add a new line character in Linux?

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.

How do I add a new line in bash?

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.


2 Answers

Try $'\n':

VAR=a VAR="$VAR"$'\n'b echo "$VAR" 

gives me

a b 
like image 140
vmpstr Avatar answered Oct 11 '22 05:10

vmpstr


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.)

like image 39
William Pursell Avatar answered Oct 11 '22 05:10

William Pursell