Edit Shell Script While It's Running

What will happen when I edit a script while it's running?

Let's test it.

Create a script test.sh:

#!/usr/bin/env bash

sleep 1
echo 'echo "executed overwritten"' >> "$0" # append to self
sleep 1
echo 'executed original'

and execute it:

$ bash --version
GNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
$ chmod +x test.sh
$ ./test.sh
executed original
executed overwritten
$

Notice that bash continued reading the modified file. It maintains its current position in the file (in bytes) when the file changes.

As a demonstration, the script

#!/usr/bin/env bash

sleep 1
dd if=/dev/urandom bs=1024 count=1 of="$0" &>/dev/null # overwrite self
sleep 1
echo 'executed original'

gives the output

$ ./test.sh 
./test.sh: line 6: syntax error near unexpected token `$'\311\262\203''
./test.sh: line 6: `��z�eп9)�v��▒y�a��44'{�d��4\:�A����˷���&�$�����l�
@(ɲ��4��OϹI�n>��7��P�M�a��X.�S�a���V�m�~O<��{}������J��$��TOtRd��Nw�&��B�Dz�▒��-��<`�P<?N��▒rT�Jq�L����JY�*hz���M�����i�⫣��S+�����\��c���m�NKV�8|��xvX}�׉V����PTd䊄�9��7���|��/��X��
��0¤k��_�R���e�*���(qu:UUɭp/j��n��bŇ_�UR?3▒�▒�%Rn�|DE$8�QbaK)A�{ ��O>9��A�����lt�����g)s��O��M��@���w��|�����N��,W'

Notice that it attempted to execute the random gibberish.

(This is Ubuntu 12.04. Behavior may vary with other shells.)

Edit shell script and python script while it's running

The bash script is already loaded in memory and executing and the results will not be affected until the next run. The python script is not loaded yet and is loaded in memory after you modify it.

If you do the reverse and launch the bash script from an equivalent python script, you will get the same behavior in reverse.

EDIT 05/10/2020

As pointed out by Gordon Davisson;

"Different versions of bash do different things. Some read the file byte-by-byte as they execute it, some I think load it in 8KB blocks (not necessarily the whole file), some do even more complicated things (AIUI it can also depend on the OS they're running under). See my answer Overwrite executing bash script files. Net result: do not count on any particular behavior."

That said, the OP's OS behavior seem to indicate a complete load of the script which explain the current behavior, albeit does not guarantee it.



Related Topics



Leave a reply



Submit