Replies: 1 comment 6 replies
-
Some thoughts in no particular order: exit - In regards to placing exec - I was facing similar problems in Ruby. The way I solved it was using #!/usr/bin/env bash
# test.sh
echo "hello"
exec bash -c "echo # running update >> test.sh"
echo "world" For example, here we create a temporary update script and #!/usr/bin/env bash
# test2.sh
cat << 'EOF' > ./update.sh
#!/usr/bin/env bash
echo "Updating"
echo "# some updated lines" >> test2.sh
EOF
# Run the update script
chmod +x ./update.sh
exec ./update.sh |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
So, Bash has a unique way of executing scripts compared to other languages. It executes commands line-by-line while it is reading lines. Which means if your script changes while it's being executed, Bash will just continue to read the same file, reading and executing commands from the new updated version. This leads to some interesting behavior, including making it really hard to predict what line of code will be executed next after the script is updated.
Compare that to other languages, which usually read and parse the whole file before beginning execution: File changes don't affect processes that are already running.
A workaround to make Bash behave like other languages is to use a pattern like this:
This forces Bash to parse the entire
main
function and execute it as a whole, regardless if the script changes during execution. And theexit
call at the end ofmain
makes sure that Bash won't execute any new lines that might appear after themain
call.Which leads me to my actual use case: I want to use rush (which is built with Bashly) to update rush. Bashly almost uses the pattern above, which is great. However it doesn't put an
exit
command at the end ofrun
, so updating rush via rush is still pretty unsafe.I know this is a pretty narrow edge case, but it would make sense to support scripts than can safely self-update. Thoughts?
Beta Was this translation helpful? Give feedback.
All reactions