逃避双人双语和单句话
我有一个 Cron 作业,每季度在每月的第一个星期日运行:
0 0 1-7 3,6,9,12 * [ "$(date '+\%a')" == "Sun" ] && /script.sh
现在我想使用 echo 自动安装它,例如:
(crontab -l ; echo "0 0 1-7 3,6,9,12 * [ "$(date '+\%a')" == "Sun" ] && /script.sh") | crontab -
虽然转义 \"Sun"\
工作正常,但我无法转义 "$(date '+\%a')"
因为这是双引号 echo 命令中单引号和双引号与 \
的混合。
I have a Cron Job running quarterly on every first Sunday of the Month:
0 0 1-7 3,6,9,12 * [ "$(date '+\%a')" == "Sun" ] && /script.sh
Now I want to install it automatically using echo like:
(crontab -l ; echo "0 0 1-7 3,6,9,12 * [ "$(date '+\%a')" == "Sun" ] && /script.sh") | crontab -
while escaping \"Sun"\
works fine I can't escape "$(date '+\%a')"
as this is a mix of single and double quotes with \
within double quoted echo command.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不需要使用疯狂的逃跑。使用
bash
提供的[[ ... ]]
而不是旧的(且容易出错)[ ... ]
:使用:
所以 要自动安装它,请使用:
PS:请确保在 crontab 文件中的该行之前设置
SHELL=/bin/bash
。You don't need to use crazy escaping. Use
[[ ... ]]
provided bybash
instead of old (and error prone)[ ... ]
:So use:
And to install it automatically use:
PS: Make sure to set
SHELL=/bin/bash
in the crontab file before this line.您可以使用此处文档来避免引用 crontab 条目:
printf
而不是echo
来输出 crontab 条目。date '+\%a'
生成类似于\Sun
的输出(对于date
程序的某些版本)。您可能需要日期“+%a”
。(更新:戈登·戴维森 (Gordon Davisson) 的评论解释了
date 中的反斜杠'+\%a'
是必需的,因为该命令位于crontab
中。)%a
日期格式生成的字符串取决于语言环境。它可能不是周日的Sun
。使用数字日期更安全(例如[ "$(date '+%w')" -eq 0 ]
)。==
与[...]
一起使用在 shell 之间不可移植。使用=
除非您确定 crontab 条目只能使用 Bash 运行。You could use a here document to avoid having to quote the crontab entry:
printf
instead ofecho
to output the crontab entry.date '+\%a'
produces output like\Sun
(for some versions of thedate
program). You probably wantdate '+%a'
.(Update: the comment by Gordon Davisson explains that the backslash in
date '+\%a'
is necessary because the command is in acrontab
.)%a
date format depends on the locale. It could be something other thanSun
for Sunday. It's safer to use a numeric day (e.g.[ "$(date '+%w')" -eq 0 ]
).==
with[...]
is not portable between shells. Use=
unless you are sure that the crontab entries will only be run with Bash.