2015-10-26 124 views
5

如果用户或cronjob执行Linux shell脚本,是否可以识别?如何检查Linux shell脚本是否由cronjob执行?

如果是,我该如何识别/检查,如果shell脚本是由cronjob执行的?

我想在我的脚本中实现一个功能,它返回一些其他消息,就好像它是由用户执行的。像这样,例如:

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 
+0

使用环境变量? '* * * * * CRON_FIRED = true/path/to/myscript'但是请注意,语法是[受cron实现的影响](http://stackoverflow.com/a/10657111/2908724),也可以被愚蠢地愚弄。 – bishop

回答

6

一个选项是测试脚本是否附加到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)发射作业也无终端运行,虽然没有明确由cron。

还要注意,这是POSIX,而不是Linux-(或bash-)特定的。

+0

Thx似乎是解决方案。我总是忘记,在哪里我可以找到可用'if'测试参数列表,如-n,-x,-f以及您使用的-t。我在哪里可以找到这个列表?我想读一下,'-t'究竟意味着什么。 POSIX的意思是,它适用于每个Linux Distributation,对吧? – user2966991

+1

@ user2966991这将是http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html或'man 1p test' –

+1

@ user2966991在这种情况下,POSIX意味着它应该可以与任何POSIX兼容的shell一起工作。这些shell也可以在Windows上找到,从技术上讲,你可以有一个没有POSIX shell的Linux发行版。 –