I want to echo a new line to a file in between variables in a shell script. Here's my code:
var1="Hello" var2="World!" logwrite="$var1 [Here's where I want to insert a new line] $var2 echo "$logwrite" >> /Users/username/Desktop/user.txt
Right now, when I run my script, the file user.txt shows this:
Hello World!
I want it to show:
Hello World!
How do I do this??
EDIT: Here's my shell script:
echo -n "What is your first name? " read first echo -n "What is your last name? " read last echo -n "What is your middle name? " read middle echo -n "What is your birthday? " read birthday echo -e "First Name: $first /nLast Name: $last /nMiddle Name: $middle /nBirthday: $birthday" >> /Users/matthewdavies/Desktop/user.txt qlmanage -p "~/Desktop/user.txt"2
2 Answers
var1="Hello"
var2="World!"
logwrite="$var1\n$var2"
echo -e "$logwrite" >> /Users/username/Desktop/user.txtExplanation:
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.txtor even:
echo -e "Hello\nWorld! " >> /Users/username/Desktop/user.txt 5 var1='Hello'
var2='World!'
echo "$var1" >> /Users/username/Desktop/user.txt
echo "$var2" >> /Users/username/Desktop/user.txtor actually you don't need vars:
echo 'Hello' >> /Users/username/Desktop/user.txt
echo 'World!' >> /Users/username/Desktop/user.txtthere 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"
3