Shell script echo new line to file
Become or hire the top 3% of the developers on Toptal https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping
--
Chapters
00:00 Question
00:51 Accepted answer (Score 47)
01:29 Answer 2 (Score 5)
02:44 Thank you
--
Full question
https://superuser.com/questions/313938/s...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#shell #shellscript #echo
#avk47
ACCEPTED ANSWER
Score 48
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
ANSWER 2
Score 5
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"