如何注释匹配特定单词的 crontab 条目,然后恢复为原始状态

huangapple go评论80阅读模式
英文:

how to comment crontab entries that match word and then restore to original

问题

  1. 我在crontab中有以下内容:

这是AAA

0 0,8 * * * ${HOME}/script.sh AAA

这是BBB

0 0,8 * * * ${HOME}/script.sh BBB

  1. 我有一个脚本,需要在开始时将BBB任务注释掉,完成后将crontab还原为原始状态。
  2. 脚本开始时需要有如下crontab

这是AAA

0 0,8 * * * ${HOME}/script.sh AAA

这是BBB

#0 0,8 * * * ${HOME}/script.sh BBB

  1. 脚本结束后将crontab还原为以下内容:

这是AAA

0 0,8 * * * ${HOME}/script.sh AAA

这是BBB

0 0,8 * * * ${HOME}/script.sh BBB

  1. 我能够将crontab复制到一个文件,然后使用sed进行修改(有没有办法在一行中完成?)

crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/'' crontab.bak

  1. 然后如何去掉注释?
  2. 谢谢!

crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/'' crontab.bak

  1. <details>
  2. <summary>英文:</summary>
  3. I have this in crontab:

this is AAA

0 0,8 * * * ${HOME}/script.sh AAA

this is BBB

0 0,8 * * * ${HOME}/script.sh BBB

  1. I have a script that need to comment out BBB job at beginning and once finish put crontab as it was originally
  2. at beginning of script need to have crontab like this:

this is AAA

0 0,8 * * * ${HOME}/script.sh AAA

this is BBB

#0 0,8 * * * ${HOME}/script.sh BBB

  1. once script ends restore crontab to this:

this is AAA

0 0,8 * * * ${HOME}/script.sh AAA

this is BBB

0 0,8 * * * ${HOME}/script.sh BBB

  1. I was able to copy crontab to a file and then modifying file with sed (any idea how to do this in one line?)

crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/' crontab.bak

  1. and how to remove the comment?
  2. thanks!

crontab -l > crontab.bak
sed -i 's/^[^#]*BBB/#&/' crontab.bak

  1. </details>
  2. # 答案1
  3. **得分**: 1
  4. 使用 `sed`,如果注释存在,这将删除它(反之亦然),然后将文件加载回您的 crontab。
  5. ```bash
  6. $ sed -E '/BBB$/{n;/^#/{s///;q};/^#/!{s/^/#/;q}};' > crontab.bak <(crontab -l) ; crontab crontab.bak
英文:

Using sed, if the comment is present, this will remove it (and vice versa) and load the file back to your crontab.

  1. $ sed -E &#39;/BBB$/{n;/^#/{s///;q};/^#/!{s/^/#/;q}};&#39; &gt; crontab.bak &lt;(crontab -l) ; crontab crontab.bak

答案2

得分: 0

这个答案继续自@HatLess的回答。在不使用临时文件的情况下使用单个管道:

  1. crontab -l | sed ... | crontab -

不过,如果出现问题,你可能希望有一个备份:

  1. crontab -l | tee crontab.bak | sed ... | crontab -
英文:

This answer follows on from @HatLess's one. Using a single pipeline without a temp file:

  1. crontab -l | sed ... | crontab -

You might want a backup in case things go wrong though:

  1. crontab -l | tee crontab.bak | sed ... | crontab -

huangapple
  • 本文由 发表于 2023年2月24日 01:18:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75548197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定