Updating a running bash file

▼魔方 西西 提交于 2021-01-28 05:44:48

问题


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 (simplified version)

# 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

Then I call example.sh update (which calls the function) so it executes the git pull.

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:

error: unable to create file example.sh: Permission denied

probably because it's in use for still running example.sh update and waiting for git pull to finish.

I already tried

( cd "$dir" && git pull & )

and

bash -c "sleep 1 && cd \"$dir\" && git pull" &

How can I fire a new process to update this repo so that no files are in use at the moment of git pulling?


回答1:


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.

At the beginning of your script, add

#! /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
# ...

This will replace the script's process with a new bash process which reads commands from its arguments and not from a file.

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.



来源:https://stackoverflow.com/questions/55728533/updating-a-running-bash-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!