我有一个bash脚本,每天晚上通过cron备份Minecraft服务器,脚本如下:
#!/usr/bin/env bash
#
# Usage:
# backup_server.sh <name>
#
# Options:
# -h, --help Show this screen.
# --version Show version.
set -euo pipefail
#shellcheck disable=SC1091
source /opt/minecraft/bin/docopts.sh
source /opt/minecraft/scripts/mc_functions.sh
rcon() {
local command=$1
if [ "$server_name" != "proxy" ] && mc_server_online "$server_name" ; then
/opt/minecraft/bin/mcrcon "$command"
fi
}
main() {
local version='1.0.0'
usage=$(docopt_get_help_string "$0")
eval "$(docopts -A ARGS -V "$version" -h "$usage" : "$@")"
local server_name=${ARGS[<name>]}
local source=$MC_SERVER_ROOT/$server_name
local destination=$MC_BACKUP_ROOT/$server_name
[ -d "$source" ] || {
printf "A server named '%s' does not exist.\n" "$server_name" >&2
exit 1
}
mc_set_rcon_credentials "$server_name" || {
printf "Failed to set the rcon credentials for the server '%s'.\n" "$server_name" >&2
exit 1
}
rcon "save-off"
rcon "save-all"
mkdir -p "$destination"
tar -cpvzf "$destination/$(date +%F-%H-%M).tar.gz" "$source" >&2
rcon "save-on"
unset MCRCON_PASS
unset MCRCON_PORT
find "$MC_BACKUP_ROOT" -type f -mtime +7 -name "*.gz" -delete
}
main "$@"
以前,我没有完全限定source
命令中脚本的路径或mcrcon的路径,因为这些路径在我的路径中,当从终端运行脚本时,脚本找到它们没有问题。
然而,当从cron运行脚本时,脚本会失败,因为它找不到可执行文件或脚本。我猜这是因为cron不能读取或使用$PATH
?
我的crontab看起来像这样:
0 1 * * * bash /opt/minecraft/scripts/backup_server.sh proxy
# There's a few other commands here identical to this one except for the server name.
有人能解释一下为什么我需要在使用cron时完全限定脚本/可执行文件的路径,或者建议一种不那么乏味的方法来完成这个任务吗?
1条答案
按热度按时间5t7ly7z51#
您可以尝试将Bash作为登录shell运行:
这样,与您习惯的环境相比,您将获得更完整的环境。
请参阅手册了解说明:https://www.man7.org/linux/man-pages/man1/bash.1.html#INVOCATION