[FIX] filesystem – Can I modify a bash script (.sh) file while it is running?
The shell is not like other scripting languages.
The shell reads and executes commands one by one, so the simple answer is “yes, editing a running script can affect it”, but it’s important to understand the details.
If you are careful, you can add lines to the end of a running script, and they will be run after the other commands already in the script.
echo "echo 'This extra command will also run.'" >> yourscript.sh
Some editors may write a new file (inode) with the same name as the old one; any changes made that way won’t affect what the shell reads (which is why those editors do that). Thus confounds some attempts at testing this.
But as long as you’re still dealing with the same inode, the running shell will be affected if the script is altered beyond the point it has read up to – unless of course it invokes
exit before then.
Reading is typically done 4KiB blocks, so that small scripts may appear to run unaffected, but when it’s close to the end of file, the shell (like all text processing programs) will read whatever it can get. This “short read” does not by itself signal end-of-file, and the shell will continue to read until it reads no bytes at all. Thus, if the file gets longer while the shell is reading it, the shell will read the new data.
It’s important to note at this point that the shell won’t attempt to read more data until it needs to, either to finish parsing a compound command, or because it’s simply run all the previous commands. That delay is where you have a chance to alter the file containing the script.
So any change that makes the file longer will almost always have some effect.
Editing a file and inserting N bytes in the middle will reposition the last N bytes of the file to just beyond where the end-of-file used to be. Those bytes will be read as “new” by the shell, even if it has just read them at their previous position.
And to complicate things further, because the block and line boundaries probably won’t coincide, the shell may read starting part way through a line, giving rise to the “gibberish effect”. This can happen happen if you add or delete lines that are before where the shell has read up to.