0

I'm trying to use this line in a bash script to update my cron jobs:

(sudo crontab -l ; echo "0 6 1-7 * * [ $(/usr/bin/date +\%u) == 7 ] && sh $script_path > $log_path") | sort - | uniq - | sudo crontab -

Prior to this, $script_path and $log_path have been defined. I know this works in general. I just have one hang up. $(/usr/bin/date +\%u) resolves to an empty string when the crontab file is written to. I need that literal text to remain in place.

(Not that is really matters, but the point of that is to verify the day of the week. This job is to be run on the first Saturday of the month).

How do I "escape" that whole substring?

1

You may escape each problematic character with \ (see Hunter.S.Thompson's answer) or just use single quotes, the enclosed string being written as is:

(sudo crontab -l ; echo '0 6 1-7 * * [ $(/usr/bin/date +\%u) == 7 ] && sh '"$script_path > $log_path") | sort -u | sudo crontab -

I personally tend to avoid escaping characters, as I think it harms readability.

| improve this answer | |
  • The answer from @Hunter.S.Thompson was good too. I gave you the edge for avoiding the escape character. So I understand, a single quoted string is a hard literal then? – BuvinJ Sep 14 '17 at 17:33
  • 1
    @BuvinJ Absolutely. There is no way to escape anything in a single quoted string. That really simplifies things most of the time... unless you want to enclose a single quote in that string... (you can't) – xhienne Sep 14 '17 at 21:09
  • Thanks @xhienne 1. I didn't know that, and it's VERY useful! – BuvinJ Sep 14 '17 at 22:39
2

You can use \ before the dollar sign to get its literal value.

(sudo crontab -l ; echo "0 6 1-7 * * [ \$(/usr/bin/date +\%u) == 7 ] && sh $script_path > $log_path") | sort - | uniq - | sudo crontab -
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.