如何检查 Linux shell 脚本是否由 cronjob 执行?
How-to check if Linux shell script is executed by a cronjob?
是否可以识别 Linux shell 脚本是由用户或 cronjob 执行的?
如果是,如果 shell 脚本由 cronjob 执行,我如何 identify/check?
我想在我的脚本中实现一个功能,即 returns 一些其他消息,就好像它是由用户执行的一样。例如:
if [[ "$type" == "cron" ]]; then
echo "This was executed by a cronjob. It's an automated task.";
else
USERNAME="$(whoami)"
echo "This was executed by a user. Hi ${USERNAME}, how are you?";
fi
一个选项是测试脚本是否附加到 tty。
#!/bin/sh
if [ -t 0 ]; then
echo "I'm on a TTY, this is interactive."
else
logger "My output may get emailed, or may not. Let's log things instead."
fi
请注意,at(1)
触发的作业也是 运行 没有 tty 的,尽管不是专门由 cron 触发的。
另请注意,这是 POSIX,而不是 Linux-(或 bash-)特定的。
是否可以识别 Linux shell 脚本是由用户或 cronjob 执行的?
如果是,如果 shell 脚本由 cronjob 执行,我如何 identify/check?
我想在我的脚本中实现一个功能,即 returns 一些其他消息,就好像它是由用户执行的一样。例如:
if [[ "$type" == "cron" ]]; then
echo "This was executed by a cronjob. It's an automated task.";
else
USERNAME="$(whoami)"
echo "This was executed by a user. Hi ${USERNAME}, how are you?";
fi
一个选项是测试脚本是否附加到 tty。
#!/bin/sh
if [ -t 0 ]; then
echo "I'm on a TTY, this is interactive."
else
logger "My output may get emailed, or may not. Let's log things instead."
fi
请注意,at(1)
触发的作业也是 运行 没有 tty 的,尽管不是专门由 cron 触发的。
另请注意,这是 POSIX,而不是 Linux-(或 bash-)特定的。