更新正在运行的bash文件 [英] Updating a running bash file
问题描述
我在bash脚本中具有以下功能.我们将此脚本称为 example.sh
.它位于应该更新的git存储库中.
I have the following function in a bash script. Let's call this script example.sh
. It's inside a git repository that should update.
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
.
Then I call example.sh update
(which calls the function) so it executes the git pull
.
现在的问题是,当 example.sh
中发生更改时,它需要自我更新.Linux没问题,但是GitBash(Windows ..)抱怨说:
Now the issue is when there's a change in example.sh
, it needs to update itself. Linux has no problem doing that, but GitBash (Windows..) complains saying:
错误:无法创建文件example.sh:权限被拒绝
error: unable to create file example.sh: Permission denied
可能是因为它仍用于仍在运行 example.sh更新
并等待 git pull
完成.
probably because it's in use for still running example.sh update
and waiting for git pull
to finish.
我已经尝试过
( cd "$dir" && git pull & )
和
bash -c "sleep 1 && cd \"$dir\" && git pull" &
如何触发新流程来更新此存储库,以便在 git pull
ing时不使用任何文件?
How can I fire a new process to update this repo so that no files are in use at the moment of git pull
ing?
推荐答案
由于Windows缺少GitBash,因此我无法测试以下建议.如果您能给我一些反馈,我会很高兴.
For the lack of GitBash for Windows I wasn't able to test the following suggestion. I would be happy if you could give me some feedback.
在脚本的开头,添加
#! /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
进程替换脚本的进程,该进程从其参数而不是从文件中读取命令.
This will replace the script's process with a new bash
process which reads commands from its arguments and not from a file.
请注意,您在 bash -c
内无法检测到脚本的目录.如果需要,可以将目录作为参数传递.或者,您可以 cd
before exec
,这样新进程将在正确的目录中启动.
Please note that your detection of the script's directory probably won't work inside bash -c
. You can pass the directory as an argument if needed. Alternatively, you can cd
before exec
such that the new process starts in the correct directory.
这篇关于更新正在运行的bash文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!