【问题标题】:Why can I create but not write to a file from a Bash script within a cronjob?为什么我可以从 cronjob 中的 Bash 脚本创建文件但不能写入文件?
【发布时间】:2014-09-13 12:05:56
【问题描述】:

我有一个简单的 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 中的临时文件吗?

谢谢!

【问题讨论】:

  • 您应该指定countingScript.sh 的完整路径。如果它在您的主目录中,您可能仍需要使用./countingScript.sh~/countingScript.sh 指定路径。

标签: bash sed cron


【解决方案1】:

由于以下两个原因之一,它可能不会写入您的 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 文件的路径。您会惊讶地发现它们工作得很好。

【讨论】:

  • 实际上我的真实脚本中有完整的临时文件路径,但不是countingScript.sh。改变它并添加一个源 /root/.bash_profile 让它工作。感谢 user854 和 dg99! ...但是如果我可以随时以 root 用户身份从命令行(没有完整路径)运行countingScript.sh,这是否意味着通过cron 运行的东西不会在与root 相同的环境中运行脚本?
猜你喜欢
  • 1970-01-01
  • 2021-12-30
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-25
  • 2019-08-01
相关资源
最近更新 更多