为什么我可以在cronjob中从Bash脚本创建文件,但不能写入文件?



我有一个从命令行运行的简单Bash脚本。它需要写入靠近脚本开头的两个临时文件。当我将它放入cronjob中时,它将创建临时文件,但不会向其中写入任何数据。文件的大小为零。每次重启cron作业时,我希望覆盖临时文件。

cron条目基本上是这样的:

0 */4   *   *   *   /opt/myscripts/boringScript.sh 

脚本中为:

...
echo "Starting boring inventory script"  >>  /opt/myscripts/boringScriptLog.out
countingScript.sh | grep $paramONE | sed s# ##g  >  tempResults1.txt
countingScript.sh | grep $paramTWO | sed s# ##g  > tempResults2.txt

do 
   // more stuff with the above temp files
   ...
done
...

任何想法为什么它不会写任何数据到我的临时文件在cron?

谢谢!

由于以下两个原因之一,它可能不会写入tempResults文件:

  1. 运行countingScript.sh的用户id没有对这些文件的写权限
  2. 运行countingScript.sh的用户id在其运行的目录中没有写权限。

在处理cron时,为所有读取或写入的脚本和文件指定绝对路径是一个非常,但是非常非常好的主意。我在你的剧本里没有完全看到。

例如,您正在指定/opt/myscripts/boringScriptLog.out的完整路径,但依赖于当前工作目录中的countingScript.sh, tempResults1.txt和tempResults2.txt,并且您的用户对它们具有写访问权限。

由于脚本正在运行,您至少拥有countingScript.sh所在目录的读和执行权限,但没有写权限。

尝试使用

/path/to/my/countingScript.sh | grep $paramONE | sed s# ##g  >  /tmp/tempResults1.txt
/path/to/my/countingScript.sh | grep $paramTWO | sed s# ##g  >  /tmp/tempResults2.txt

,并修改脚本中引用这些tempResults文件的其余部分的路径。你会惊讶地发现它们工作得很好。

最新更新