我有一个包含以下几行的 shell 脚本(完整脚本位于帖子末尾):
CRON_BCK_CMD=/home/user/bck.sh
CRON_CONF=" */30 * * * * $CRON_BCK_CMD"
但是当我简单地在 shell 中运行这些然后echo $CRON_CONF
我得到
*/30 ... /home/user/bck.sh
其中...
代表 /home/user 列出的所有文件,例如*/30 bck.sh bck-ssh.sh Documents davmail.log.../home/user/bck.sh
我认为该脚本曾经在我的另一台机器上运行过。我该如何做我明显想做的事情?
# SETUP
# CRON_BCK_CMD sets the full path to the backup script
CRON_BCK_CMD=/home/user/bck.sh
# CRON_CONF sets the configuration line for cron, the time is set as:
# minute hour day_of_month month day_of_week
# * means any value, eg. 15 * * * * would mean backup at any hour, any day, when minute on the clock equals 15
# repetition can be managet by /, eg. */15 * * * * means backup every 15 minutes
CRON_CONF=" */30 * * * * $CRON_BCK_CMD"
# SETUP END
CRON_IS_BCK_CMD=$(crontab -l 2>/dev/null | grep $CRON_BCK_CMD) || true
if [[ ! $CRON_IS_BCK_CMD ]]
then
echo "No entry for backup found in crontab, do you want to schedule?"
read -p "y/n (y) " REPLY
if [[ $REPLY =~ ^[n|N]$ ]]
then
echo "Nothing to do, exitting..."
exit 0
fi
(crontab -l ; echo "$CRON_CONF") | crontab -
else
echo "Found crontab entry, do you want to stop schedule?"
read -p "y/n (y) " REPLY
if [[ $REPLY =~ ^[n|N]$ ]]
then
echo "Nothing to do, exitting..."
exit 0
fi
crontab -l | grep -v $CRON_BCK_CMD | crontab -
fi
答案1
使用引号将变量表示为字符串,而不是变量的原始来源。因为否则,如果星号跟在斜杠后面,则在目录路径规范中将被视为“星号约定” - 因此星号将代表指定目录中的所有文件。
如果您想通过 CRON 运行 shell 脚本,对于某些情况下的问题,还建议通过 shell 解释器 ( /bin/bash -c /home/script.sh &
) 运行脚本,并在后台将其作为任务运行(&
最后)。
#!/bin/bash
# SETUP
# CRON_BCK_CMD sets the full path to the backup script
CRON_BCK_CMD="/home/user/bck.sh"
# CRON_CONF sets the configuration line for cron, the time is set as:
# minute hour day_of_month month day_of_week
# * means any value, eg. 15 * * * * would mean backup at any hour, any day, when minute on the clock equals 15
# repetition can be managet by /, eg. */15 * * * * means backup every 15 minutes
CRON_CONF="*/30 * * * * /bin/bash -c $CRON_BCK_CMD &" # change the Shell to the one used in your Linux (dash, sh, ash, ...)
# SETUP END
if crontab -l | grep "$CRON_BCK_CMD" > /dev/null; then
echo "Found crontab entry, do you want to stop schedule?"
read -p "y/n (y): " REPLY
if [ "$REPLY" != "n" ]; then # if the "ENTER" key was pressed or the "y" character was typed...
crontab -l | grep -v "$CRON_BCK_CMD" | crontab -
fi
else
echo "No entry for backup found in crontab, do you want to schedule?"
read -p "y/n (y): " REPLY
if [ "$REPLY" != "n" ]; then # if the "ENTER" key was pressed or the "y" character was typed...
(crontab -l; echo "$CRON_CONF") | crontab -
fi
fi
exit 0