繁体   English   中英

crontab在shell命令中看不到$ 1参数

[英]crontab doesn't see the $1 parameter by shell command

我编写了一个小的bash脚本,其中添加了一个crontab,该crontab每分钟运行另一个bash脚本,并带有在运行第一个脚本时设置的参数。

因此,这是您像./main.sh parameter1一样运行的main.sh ,并添加了一个crontab;

function cronjobs {
  if ! crontab -l | grep "~/runthis.sh"; then
    (crontab -l ; echo "* * * * * ~/runthis.sh $1") | crontab -
  fi
}

但是,当我检查crontab -e它似乎没有parameter1 ,仅添加了此部分; * * * * * ~/runthis.sh

我怎样才能解决这个问题?

您是否cronjobs参数$1传递给脚本main.sh的函数cronjobs

我测试了您的代码,它可以正常工作。

文件main.sh

#!/bin/bash
function cronjobs {
  if ! crontab -l | grep "~/runthis.sh"; then
    (crontab -l ; echo "* * * * * ~/runthis.sh $1") | crontab -
  fi
}

cronjobs "$1"
#        ^^^^ here

./main.sh foobar

您将在crontab -l看到一行

* * * * * ~/runthis.sh foobar

更新:

在bash脚本中,除非有特殊原因,否则应对变量使用双引号。

当前脚本,如果我们运行./main.sh "foo bar"

我们将得到

* * * * * ~/runthis.sh foo bar

这意味着脚本~/runthis.sh将获得两个参数foobar ,而不是一个foo bar

如果最后一行是cronjobs $1 ,请运行./main.sh "foo bar"

crontab -l ,我们将获得:

* * * * * ~/runthis.sh foo

更新脚本main.sh

#!/bin/bash
function cronjobs {
  if ! crontab -l | grep "~/runthis.sh"; then
    (crontab -l ; echo "* * * * * ~/runthis.sh \"$1\"") | crontab -
  fi                                         #  ^^^^^^^ double quotes
}

cronjobs "$1"
#        ^^^^ here

./main.sh "foo bar"

会得到

* * * * * ~/runthis.sh "foo bar"

更新:

如果我们要添加具有不同参数的作业

main.sh

#!/bin/bash
function cronjobs {
  if ! crontab -l | grep "~/runthis.sh \"$1\"\$"; then
                                     # ^^^^^^^^ also check the parameter
    (crontab -l ; echo "* * * * * ~/runthis.sh \"$1\"") | crontab -
  fi                                         #  ^^^^^^^ double quotes
}

cronjobs "$1"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM