【问题标题】:shell script runs manually, but fails on crontabshell 脚本手动运行,但在 crontab 上失败
【发布时间】:2017-10-09 07:25:54
【问题描述】:

我编写了一个 shell 脚本来从远程服务器复制文件并将同一个文件转换为另一种格式。转换后,我将使用 sed 命令编辑文件。脚本在手动执行时运行成功,但在通过 crontab 执行时失败。

Crontab 条目是: */1 * * * * /script/testshell.sh

下面是shell脚本代码:

 #!/bin/bash

 file="/script/test_data.csv" if [ -f "$file" ] then
         echo " file is present in the local machine  " else
         echo " file is not present in the local machine "
         echo " checking the file is present in  the remote server  "

         ssh user@IP 'if [ -f /$path ]; then echo File found ; else echo File not found; fi' fi

 if [ -f "$file"] then
         rm -f test_data.csv fi

 scp -i /server.pem  user@IP:/$path


 file="/script/test_data.csv" if [ -f "$file" ] then
         echo "$file found." else
         echo "$file not found." fi

 if [ -f "$file" ] then echo " converting csv to json format ....." fi

 ./csvjson.sh input.csv  output.json


 sed  -e '/^$/d'  -e  's/.*/&,/; 1 i\[' ./output.json |  sed ' $ a \]'
 hello.json

手动运行脚本后,它可以完美运行。但不适用于 crontab。

【问题讨论】:

  • 尽量使用绝对路径
  • 谢谢。现在它的工作。我到处都给出了绝对路径。
  • 这是一个糟糕的主意,只需在脚本开头正确设置 PATH 即可。

标签: shell sed


【解决方案1】:

cron 什么不起作用,输出是什么 cron 有什么错误?

尝试一些事情:

cron 默认情况下不会运行您的配置文件,因此如果您的脚本需要从中设置任何内容,请将其包含在 crontab 命令中,例如

"../.bash_profile;/script/testshell.sh"

我在任何地方都看不到 $path 设置,虽然它用于测试是否存在文件,但您是否在某处手动设置,因此不会从 cron 设置?

您的一些脚本和文件被指定为在当前目录 (./) 中,来自 cron,这将是您的主文件夹,是正确的还是您需要更改脚本中的目录或使用它们的路径?

希望有帮助

【讨论】:

  • 现在 cronjob 运行良好。我到处都给出了绝对路径。
猜你喜欢
  • 2013-01-14
  • 2021-05-01
  • 1970-01-01
  • 2014-01-02
  • 2013-10-18
  • 2016-12-18
  • 2021-03-12
  • 1970-01-01
相关资源
最近更新 更多