【问题标题】:List all cronjobs if there are any without superfluous info列出所有 cronjobs(如果有没有多余信息)
【发布时间】:2016-05-30 04:57:21
【问题描述】:

尝试输出 cronjobs 列表,而不是用户列表。 crontab -l 的原始输出太脏了,我似乎无法清理它。我用sudo script.shsu 运行它,然后运行它。我也尝试过调用它sudo script.sh | grep -v no。我很困惑为什么这不起作用:

#!/bin/bash
#Trying to show all cronjobs but no extraneous info
#
# This shows "no crontab for USER" for every USER without
# a crontab - I only want to see actual cronjobs, not a long
# list of users without crontabs
echo "Here is the basic output that needs manipulation:
"
for USER in `cat /etc/passwd | cut -d":" -f1`; do
    crontab -l -u $USER
done
#
# grep -v fails me
# (grep'ing the output of the script as a whole fails also)
echo "
trying with grep -v no on each line:
"
for USER in `cat /etc/passwd | cut -d":" -f1`; do
    crontab -l -u $USER | grep -v no
done

echo "
maybe with quotes around the no:
"
for USER in `cat /etc/passwd | cut -d":" -f1`; do
    crontab -l -u $USER | grep -v "no"
done

# string manipulation - I can't even get started
echo "
And here I try to put the commmand output into a string so I can   manipulate it further, and use an if/then/fi on the product:
"
for USER in `cat /etc/passwd | cut -d":" -f1`; do
    STRING="$(crontab -l -u $USER | grep -v no)"
    echo "STRING: $STRING"
done

顺便说一句,有没有比在每行开头粘贴 4 个空格更简单的方法来让代码在此处正确格式化?我一定已经试验了 40 分钟。不抱怨,只是问。

【问题讨论】:

  • 选择(绘制)整个代码块并按 ctrl-K 对其进行格式化。

标签: bash filter grep cron crontab


【解决方案1】:

crontab 将“no crontab for user”连接到标准错误。要摆脱这些消息,您可以运行

crontab -l -u $USER 2>/dev/null

在你的循环中。

我还建议将USER 重命名为其他名称。 USER 变量名是保留的,应该设置为您的用户(登录)名。通常,您应该使用小写的变量名,以避免这种名称冲突。

【讨论】:

  • 谢谢 - 错误,不是输出,就是这样。我通过添加适用于脚本的错误重定向来验证它,并通过回显 $? 来验证它。变量 USER 的使用不是问题,并且在它所在的 for 循环上下文中,它应该为所有用户捕获 cronjobs,这是我的意图。我点击了复选标记,但我没有看到任何事情发生。我稍后再检查。
  • 如果可以的话,我会编辑我之前的评论。重读后,我明白你对变量名的意思。很好的提示,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多