Command Line – How to Enclose in Quotes if Both Single and Double Quotes Are Used

command linequoting

I don't remember the exact commands and tricks that I use sometimes which solves much of the work, so I try to log them into a file for future reference. What I typically do is just put whole command in echo and append it to the file quickly.

This has always worked, but the following situation arrived for first time, where I was not able to do as stated above.

Successfull logging

$ echo "cat file1.txt | paste -d, - - ## Step 3 " >> ~/globalLog.txt

Got stuck here

$ echo "cat file2.txt  | sed 's/"//g' > file3.txt ## Step 2 " >> ~/globalLog.txt

The above is giving a obvious error, as the quotes are not being properly closed (dropping to the second command propmt (PS2 I guess?) for completing the command i.e. >_ in my case), the single(') quotes are being used by the sed command and the double(") quotes are being used in one the sed expression for replacement.

How would I enclose the complete command in such situation ?

Best Answer

You can entirely avoid the need to quote using here documents. Note that setting the label in single/double quotes(as in "EOF" in the example below) disables variable and command evaluation within the text.

cat <<"EOF" >>~/globalLog.txt
cat file2.txt  | sed 's/"//g' > file3.txt ## Step 2
EOF
Related Question