我在bash脚本中有以下功能。我们称这个脚本为example.sh
。它位于应该更新的git存储库中。
example.sh(简化版)
# Directory of script
dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
update() {
( cd "$dir" && git pull )
}
if [ "$1" == "update" ]; then
update
fi
然后我调用example.sh update
(调用函数),因此它执行git pull
。
现在问题是当example.sh
发生变化时,需要自行更新。 Linux没有问题,但GitBash(Windows ..)抱怨说:
错误:无法创建文件example.sh:权限被拒绝
可能是因为它仍在运行example.sh update
并等待git pull
完成。
我已经试过了
( cd "$dir" && git pull & )
和
bash -c "sleep 1 && cd \"$dir\" && git pull" &
如何启动新进程来更新此repo,以便在git pull
ing时没有文件正在使用?
由于缺少GitBash for Windows,我无法测试以下建议。如果你能给我一些反馈,我会很高兴的。
在脚本的开头添加
#! /bin/bash
self="$(sed '0,/^# ACTUALSCRIPT/d' "$BASH_SOURCE")"
exec bash -c "$self" "$0" "$@"
# ACTUALSCRIPT (keep this comment, the script relies on it)
# your old script
# ...
这将用新的bash
进程替换脚本的进程,该进程从其参数而不是从文件中读取命令。
请注意,您在bash -c
中检测到脚本的目录可能不起作用。如果需要,您可以将目录作为参数传递。或者,您可以在cd
之前使用exec
,以便新进程在正确的目录中启动。