user2500742 user2500742 -4 years ago 120
Bash Question

How can I write and append using echo command to a file

I am trying to write a script which will use echo and write/append to a file.
But I have " " in syntax already in strings .. say ..

echo "I am "Finding" difficult to write this to file" > file.txt
echo "I can "write" without double quotes" >> file.txt


Can anyone please help to understand this, really appreciated.

BR,
SM

Answer Source

If you want to have quotes, then you must escape them using the backslash character.

echo "I am \"Finding\" difficult to write this to file" > file.txt echo
echo "I can \"write\" without double quotes" >> file.txt

The same holds true if you i.e. also want to write the \ itself, as it may cause side effects. So you have to use \\

Another option would be to use The `'' instead of quotes.

echo 'I am "Finding" difficult to write this to file' > file.txt echo
echo 'I can "write" without double quotes' >> file.txt

However in this case variable substition doesn't work, so if you want to use variables you have to put them outside.

echo "This is a test to write $PATH in my file" >> file.txt
echo 'This is a test to write '"$PATH"' in my file' >> file.txt
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download