首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当直接重定向并由cron运行时,Bash脚本输出会有所不同

当直接重定向并由cron运行时,Bash脚本输出会有所不同
EN

Stack Overflow用户
提问于 2020-04-12 21:04:41
回答 2查看 27关注 0票数 0

我已经编写了以下Bash脚本

代码语言:javascript
复制
TIME=$( date '+%F %H:%M:%S')
MYRUNLEVEL=$(runlevel | cut -d ' ' -f2)

printf "Script started  successfully at  $TIME"
printf ",    Runlevel is $MYRUNLEVEL"
printf "\n"

当我从我的终端运行脚本时,就像这样

代码语言:javascript
复制
$ backup_script.sh >> test_output.txt
$ cat test_output.txt 
Script started  successfully at  2020-04-12 14:53:19,    Runlevel is 5

我正确地写出了运行级。但是当我从cronjob运行脚本时,运行级并没有写出来:

Crontab语法:

代码语言:javascript
复制
 * * * * * /home/philip//bin/backup_script.sh >> /home/philip/LinuxMint/Test_script/cron_output

文件cron_output中的输出:

代码语言:javascript
复制
Script started  successfully at  2020-04-12 14:48:01,    Runlevel is
Script started  successfully at  2020-04-12 14:49:01,    Runlevel is
Script started  successfully at  2020-04-12 14:50:01,    Runlevel is
Script started  successfully at  2020-04-12 14:51:01,    Runlevel is
Script started  successfully at  2020-04-12 14:52:01,    Runlevel is
Script started  successfully at  2020-04-12 14:53:01,    Runlevel is
Script started  successfully at  2020-04-12 14:54:01,    Runlevel is
Script started  successfully at  2020-04-12 14:55:01,    Runlevel is
Script started  successfully at  2020-04-12 14:56:02,    Runlevel is
EN

回答 2

Stack Overflow用户

发布于 2020-04-12 21:10:03

我的猜测是MYRUNLEVEL=$(runlevel | cut -d ' ' -f2)中的cut -d ' ' -f2使输出为空。试着只使用MYRUNLEVEL="$(runlevel)",看看你是否得到了你想要的。:)

票数 1
EN

Stack Overflow用户

发布于 2020-04-13 22:07:10

问题已解决:

以cronjob身份运行脚本未找到runlevel命令。通过将完整路径添加到runlevel解决了这个问题

代码语言:javascript
复制
#!/bin/bash
TIME=$( date '+%F %H:%M:%S')
MYRUNLEVEL=$(/sbin/runlevel | cut -d ' ' -f2)

printf "Script started  successfully at  $TIME"
printf ",    Runlevel is $MYRUNLEVEL "

crontab语法:

代码语言:javascript
复制
* * * * * /home/philip//bin/backup_script.sh >> /home/philip/LinuxMint/Test_script/cron_output

以cron_output格式提供输出:

代码语言:javascript
复制
Script started  successfully at  2020-04-13 16:04:01,    Runlevel is 5
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61171923

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档