【问题标题】:cron does not execute shell scriptcron 不执行 shell 脚本
【发布时间】:2022-01-21 00:28:13
【问题描述】:

我创建了一个简单的 shell 脚本,它应该通过 cron 执行,但 cron 不运行它。 我进行了谷歌搜索,发现了不同的方法,不幸的是这些方法对我不起作用。

#!/bin/bash
SHELL=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

pwd > output.txt

但是,当我在终端中运行脚本时,它工作正常

git@ubuntu-20:~/test$ ll
total 12
drwxrwxrwx  2 git git 4096 Jan 20 16:05 ./
drwxr-xr-x 12 git git 4096 Jan 20 16:04 ../
-rw-rw-r--  1 git git    0 Jan 20 16:05 file.txt
-rwxrwxrwx  1 git git   30 Jan 20 15:28 testcron.sh*
git@ubuntu-20:~/test$ cat testcron.sh 
#!/bin/bash

pwd > output.txt
git@ubuntu-20:~/test$ sh testcron.sh 
git@ubuntu-20:~/test$ ll
total 16
drwxrwxrwx  2 git git 4096 Jan 20 16:05 ./
drwxr-xr-x 12 git git 4096 Jan 20 16:04 ../
-rw-rw-r--  1 git git    0 Jan 20 16:05 file.txt
-rw-rw-r--  1 git git   15 Jan 20 16:05 output.txt
-rwxrwxrwx  1 git git   30 Jan 20 15:28 testcron.sh*
git@ubuntu-20:~/test$ 

这是crontab -e

的内容
*/1 * * * * touch /home/git/test/file.txt
*/1 * * * * /home/git/test/testcron.sh

如您所见,cron 运行第一个作业,因此将创建 file.txt。有谁知道为什么 cron 不执行 shell 脚本?

【问题讨论】:

    标签: shell ubuntu cron


    【解决方案1】:

    cron 脚本的 PWD 是 /,并且 testcron.sh 正在尝试将 output.txt 文件写入 PWD。 git用户将无权在/中写入文件

    解决方案:

    1. testcron.sh 脚本应该cd 到您有写入权限的某个目录,或者
    2. 指定应写入 output.txt 的完整路径

    【讨论】:

    • 有效!谢谢! :)