bash 使用 crontab 运行带参数的脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23682517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:27:02  来源:igfitidea点击:

Run a script with arguments using crontab

linuxbashshellshcrontab

提问by Rg90

I know this may have been answered earlier in various posts, but I've not been able to make this run myself.

我知道这可能已经在各种帖子中得到了较早的回答,但是我自己无法运行。

I have a bash script (service.sh)that I would like to run every minute. It needs an argument to be passed (startin this case).

我有一个 bash 脚本(service.sh),我想每分钟运行一次。它需要传递一个参数(在这种情况下开始)。

Using another script (test.sh)I am scheduling the cron expression for the above script:

使用另一个脚本(test.sh)我正在为上述脚本安排 cron 表达式:

echo "* * * * * /opt/service.sh start" > /opt/cronForSecops
crontab /opt/cronForSecops

I can see by using crontab -lthat this is being set correctly as:

我可以通过使用crontab -l看到它被正确设置为:

* * * * * /opt/service.sh start

However, the service.shdoes not run, and I see no logs/files being created (which the service.shfile is supposed to do, when I run it normally).

但是,service.sh没有运行,并且我没有看到正在创建的日志/文件(service.sh文件在我正常运行时应该这样做)。

Can anybody please guide me on where I am going wrong?

有人可以指导我哪里出错了吗?

回答by nettux

Try creating a simple wrapper script called /opt/start-service.shwith this content:

尝试创建一个/opt/start-service.sh使用以下内容调用的简单包装脚本:

#!/bin/sh
/opt/service.sh start

and make sure it's executable then use

并确保它是可执行的然后使用

* * * * * /opt/start-service.sh

as the crontab entry

作为 crontab 条目

回答by Eradicatore

I was having this same issue where I using the following crontab:

我在使用以下 crontab 时遇到了同样的问题:

0 23 * * * sudo -u myname /home/myname/bin/buildme.sh -f >> /home/myname/log.txt

And inside the bash script I was using this to get the -f option:

在 bash 脚本中,我使用它来获取 -f 选项:

while getopts ":f" opt; do
    case $opt in
        f)
            force_full=1
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            ;;
    esac
done

So I noticed that the option wasn't being honored when I ran this through cron for some reason. Well, adding /bin/bash to the cronjob fixed it right up. The new crontab is:

所以我注意到当我出于某种原因通过 cron 运行这个选项时,这个选项没有得到尊重。好吧,将 /bin/bash 添加到 cronjob 中就修复了它。新的 crontab 是:

0 23 * * * sudo -u myname /bin/bash /home/myname/bin/buildme.sh -f >> /home/myname/log.txt

Hope it helps!

希望能帮助到你!