How to update bash script whilst running or easily restart it?

会有一股神秘感。 提交于 2020-02-26 03:25:30

问题


I require a method to easily restart/replace bash scripts without manually stopping/starting the process over again.

Here's how my current script works:

#!/bin/sh
while true
do
  echo "1"
  java -server -Xms2G -jar game.jar nogui
done

Basically, if the game stops, it will automatically restart however, the script is already loaded into memory so if I was to modify it, I would have to manually kill the script and start it up again in order for the changes to take effect. I'm running at least 200 instances of the game server itself so, it would not be intelligent to do this manually and kill, then start each script manually again.

When the game server stops, I wish for it to update the script, here is an example of what I may want to do:

#!/bin/sh
while true
do
  echo "1"
  echo "2"
  java -server -Xms2G -jar game.jar nogui
done

However, I'd need to physically stop the script and start it again myself in order for it to add the new 'echo "2"', I need an easier way to replace the running script.

The script itself will download the updated script when the game stops (so it will automatically start again.

How can I make the script unload itself from memory, and use the new script?

If I cannot do this, is there any alternative method you can suggest?


回答1:


Call the following file myscript.sh. It reloads itself into memory every time that the game stops:

#!/bin/sh
java -server -Xms2G -jar game.jar nogui
exec /path/to/myscript.sh



回答2:


The alternative method is to use a process supervision tool such as runit, daemontools, upstart, supervisord, systemd, etc.

For any of these, you would write only the following script:

#!/bin/sh
exec java -server -Xms2G -jar game.jar nogui

...and the supervision tool would be responsible for restarting the server on exit, rereading the script (and thus responding to updates) each time it needs to be run.

These tools give you far more features than just reliable restarts -- they typically also manage logging, staged shutdown (ie. TERM + timeout + KILL), custom cleanup commands, signal hooks, etc.

See also the ProcessManagement page on the freenode #bash wiki.


If you can't use a process management system (and you really, really should!), you can have the script exec itself. That is to say:

#!/bin/sh
# ...do stuff here...
exec "$0" "$@" # and restart

Note that this is unreliable for various reasons related to BashFAQ #28.



来源:https://stackoverflow.com/questions/21654995/how-to-update-bash-script-whilst-running-or-easily-restart-it

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