Escaping Special characters

I want to append the following line to /var/spool/cron/root:

*/7 * * * * /root/'Linux CPU (EDF).sh' > /dev/null 2>&1

How to accomplish this using echo?

---------- Post updated at 04:09 PM ---------- Previous update was at 04:07 PM ----------

"Linux CPU (EDF)" is actually stored in a variable named Service_Name

---------- Post updated at 04:13 PM ---------- Previous update was at 04:09 PM ----------

I am using the command:

echo "*/7 * * * * /root/\'"$Service_Name".sh\' >/dev/null 2>&1" >> /var/spool/cron/root

Use

echo "*/7 * * * * /root/'$Service_Name'.sh > /dev/null 2>&1" >> root

It's generally not a good idea to manually modify the crontab file in this way. You should use crontab.

But the Service_Name variable contains "Linux CPU (EDF)", which has got spaces in between. I need to escape those spaces..

echo "*/7 * * * * /root/'$Service_Name'.sh > /dev/null 2>&1" >> root

You don't need to escape anything.

A=" '1 2 3' "

echo $A
'1 2 3'

I thought single quote reduces the significance of special characters including $.

Not when they're enclosed in double quotes. The opposite isn't true.

A=" '1 2 3' "

echo "$A"
'1 2 3'

A=' "1 2 3" '
echo $A
"1 2 3"

echo '$A'
$A

ksspl-RandD:~$ echo $x

ksspl-RandD:~$ echo '$x'
$x

---------- Post updated at 04:59 PM ---------- Previous update was at 04:55 PM ----------

Thanks,

If we include something inside of double-quotes, everything loses its special meaning except for the variable operator ($), the back-slash (\), the back-tick (`), and the double-quote itself.

echo " '$x' "
'  '

The single quote behaved like a normal character inside double quote..:slight_smile:

Yes.

The quote in the site you reference is clearly misleading.

We don't know what Operating System or Shell you have so this solution may not work.

Maybe you mean:

echo "*/7 * * * * \"/root/${Service_Name}.sh 2>&1 >dev/null\""

Which produces the line:

*/7 * * * * "/root/Linux CPU (EDF).sh 2>&1 >dev/null"

However. You will be well advised to avoid brackets and spaces in the filenames of shell scripts because they will drive you nuts!

I have omitted the append because the root crontab is more usually:
/var/spool/cron/crontabs/root

As hinted at earlier it is much safer to copy the crontab twice (once with a date extension and again under its correct name) to a work directory before editing the copy of "root" and then with the work directory as the current working directory publishing the edited version with "crontab root". Never issue "crontab root" unless you are in the directory containing your new crontab or the command will wipe your root crontab.

I am using centos 5.3 and the root crontab is /var/spool/cron/root.