Casper Casper - 4 months ago 10
Bash Question

How to echo exactly this string containing of special characters

I need to write exactly this string into CRON programmatically, but when I do:

echo "*/2 * * * * for i in `docker ps -a| grep -v Up | awk '{print $NF}'`; do ~/./check_service.sh $i; done >/dev/null 2>&1" >> mycron


I got:

neo4j; do ~/./check_service.sh neo4j; done >/dev/null 2>&1


So how can I escape all those special characters and prevent the script being executed.

Answer

use single quotes to prevent bash/shell expansion/evaluation. You also need to escape the single quotes around the awk script as below.

$ echo '*/2 * * * * for i in `docker ps -a| grep -v Up | awk '\''{print $NF}'\''`; do ~/./check_service.sh $i; done >/dev/null 2>&1' >> mycron