Shell script echo new line to file
var1="Hello"
var2="World!"
logwrite="$var1\n$var2"
echo -e "$logwrite" >> /Users/username/Desktop/user.txt
Explanation:
The \n
escape sequence indicates a line feed. Passing the -e
argument to echo enables interpretation of escape sequences.
It may even be simplified further:
var1="Hello"
var2="World!"
echo -e "$var1\n$var2" >> /Users/username/Desktop/user.txt
or even:
echo -e "Hello\nWorld! " >> /Users/username/Desktop/user.txt
var1='Hello'
var2='World!'
echo "$var1" >> /Users/username/Desktop/user.txt
echo "$var2" >> /Users/username/Desktop/user.txt
or actually you don't need vars:
echo 'Hello' >> /Users/username/Desktop/user.txt
echo 'World!' >> /Users/username/Desktop/user.txt
there is a problem with john t answer: if any of the vars had the \n string (or some other sequence like \t) they will get translated. one can get something similar to his answer with printf:
printf '%s\n%s\n' 'Hello' 'World!'
also hmm. i see you are composing the answer into a variable $logwrite. if this is the sole use of this variable, it seems pointless.
I think a here-doc could be more readable, specially if you have lots of line to append to the log:
cat >> /Users/username/Desktop/user.txt <<EOF
Hello
World
EOF
(this word, EOF, is a delimiter you can choose. it can be any word).
beware that the heredoc will expand $variables, like double quotes. if you don't want this, you quote the heredoc, like <<"EOF"