I'm using below command in a shell script:
我在shell脚本中使用下面的命令:
echo "1" > log.txt
if [ `ifconfig eth0 | grep 'inet addr' | cut -d ":" -f 2 |
awk {'print $1'}` = 'ipaddress' ] && [ `whoami` = 'userid' ]; then
echo "2" >> log.txt
crontab -l > Cron.txt
echo "3" >> log.txt
fi
The script runs fine when run manually but when scheduled through cron, it stucks at this IF.
手动运行时脚本运行正常,但是当通过cron进行调度时,它会停留在此IF。
cron entry: 31 11 * * * /home/abc/cron_backup.sh
Output in log.txt Manual run: prints 1,2,3 in log.txt through cron: prints 1 in log.txt
log.txt中的输出手动运行:通过cron在log.txt中打印1,2,3:在log.txt中打印1
2 个解决方案
#1
I would suggest to put as first line of your script the command interpreter line #! to make sure that sh will run it
我建议将命令解释器行#作为脚本的第一行!确保sh会运行它
after that, have you consider to use double bracket syntax [[ ]]?
之后,你考虑使用双括号语法[[]]吗?
#!/bin/sh
echo "1" > log.txt
if [[ `ifconfig eth0 | grep 'inet addr' | cut -d ":" -f 2 |
awk {'print $1'}` = 'ipaddress' ]] && [[ `whoami` = 'userid' ]]; then
echo "2" >> log.txt
crontab -l > Cron.txt
echo "3" >> log.txt
fi
#2
The problem could be with the ifconfig, grep, cut awk and whoami calls. When you run it from the command line you have your profile, which has your PATH setting.
问题可能出在ifconfig,grep,cut awk和whoami调用上。从命令行运行它时,您的配置文件具有PATH设置。
When it is run from cron, it does not have your profile. If you modify your PATH variable to point to the location of these programs then you wouldn't have that change when run from cron.
当它从cron运行时,它没有你的个人资料。如果修改PATH变量以指向这些程序的位置,那么从cron运行时就不会有这种更改。
Try putting in the full path for the each of the commands and see it that makes any difference when run from cron.
尝试为每个命令添加完整路径,并在从cron运行时看到它有所不同。
#1
I would suggest to put as first line of your script the command interpreter line #! to make sure that sh will run it
我建议将命令解释器行#作为脚本的第一行!确保sh会运行它
after that, have you consider to use double bracket syntax [[ ]]?
之后,你考虑使用双括号语法[[]]吗?
#!/bin/sh
echo "1" > log.txt
if [[ `ifconfig eth0 | grep 'inet addr' | cut -d ":" -f 2 |
awk {'print $1'}` = 'ipaddress' ]] && [[ `whoami` = 'userid' ]]; then
echo "2" >> log.txt
crontab -l > Cron.txt
echo "3" >> log.txt
fi
#2
The problem could be with the ifconfig, grep, cut awk and whoami calls. When you run it from the command line you have your profile, which has your PATH setting.
问题可能出在ifconfig,grep,cut awk和whoami调用上。从命令行运行它时,您的配置文件具有PATH设置。
When it is run from cron, it does not have your profile. If you modify your PATH variable to point to the location of these programs then you wouldn't have that change when run from cron.
当它从cron运行时,它没有你的个人资料。如果修改PATH变量以指向这些程序的位置,那么从cron运行时就不会有这种更改。
Try putting in the full path for the each of the commands and see it that makes any difference when run from cron.
尝试为每个命令添加完整路径,并在从cron运行时看到它有所不同。