Bash脚本有效,但从crontab执行时无效 [英] Bash Script works but not in when executed from crontab
问题描述
我是Linux新手,下面的脚本只是我的问题的一个示例:
I am new to linux and the script below is just an example of my issue:
我有一个脚本,该脚本在执行时可以按预期工作,但是在我执行时将其设置为通过crontab运行,由于无法将文件内容读入变量,因此无法按预期运行。
I have a script which works as expected when I execute it however when I set it to run via crontab it doesn't work as expected because it doesn't read the file content into the variable.
我有一个文件 test.txt,其中包含 abc。我的脚本将文本放入变量'var',然后将其回显到日志文件:
I have a file 'test.txt' which has 'abc' in it. My script puts the text into a variable 'var' and then I echo it out to a log file:
var=$(</home/pi/MyScripts/test.txt)
echo "$var" >/home/pi/MyScripts/log.log
当我执行它并使其回显到日志文件中时,它可以很好地工作,但是当我通过crontab对其进行设置时,它不是:
This works perfectly fine when I execute it and it echo's into the log file but not when I set it via crontab:
* * * * * /home/pi/MyScripts/test.sh
cron作业运行,并且向我发送了以下错误消息:
The cron job runs, and it sent me the following error message:
/bin/sh: 1: /home/pi/MyScripts/test.sh: Permission denied.
但是我已授予777权限:
But I have given it 777 permissions:
-rwxrwxrwx 1 pi pi 25 Jun 10 15:31 test.txt
-rwxrwxrwx 1 pi pi 77 Jun 10 15:34 test.sh
有什么想法吗?
推荐答案
当您使用其他Shell运行脚本时,会发生这种情况。对于 / bin / sh
为 dash
的系统尤其重要:
This happens when you run the script with a different shell. It's especially relevant for systems where /bin/sh
is dash
:
$ cat myscript
echo "$(< file)"
$ bash myscript
hello world
$ sh myscript
$
要修复此问题,请添加#!/ bin / bash
作为脚本的第一行。
To fix it, add #!/bin/bash
as the first line in your script.
这篇关于Bash脚本有效,但从crontab执行时无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!