What will happen when I a script file and save it when it's still running, and will it print my needed results.
Asked
Active
Viewed 5,529 times
14
-
Don't edit. If you want to modify running scripts, see [my answer](http://stackoverflow.com/questions/8335747/emacs-workflow-to-edit-bash-scripts-while-they-run/8926090#8926090) to the question [Emacs workflow to edit Bash scripts while they run](http://stackoverflow.com/questions/8335747/emacs-workflow-to-edit-bash-scripts-while-they-run). (Even if Emacs is irrelevant to you. =) – teika kazura Dec 01 '12 at 04:50
-
Lots more good discussion here: https://stackoverflow.com/q/3398258/10278 – pestophagous Mar 26 '20 at 18:04
1 Answers
20
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.)

rkeatin3
- 88
- 6

Mechanical snail
- 29,755
- 14
- 88
- 113
-
4So your answer is actually "yes, if you change the script while it is running, you change the running script"? Very cool – RandomSort Oct 12 '12 at 09:31
-
@RandomSort: But don't rely on it. Self-modifying code of this sort is totally unmaintainable. (The same thing can be done with DOS batch scripts.) – Mechanical snail Oct 12 '12 at 09:33
-
4When I ran this, the first few bytes out of /dev/urandom were `rm -rf /;`. Is that typical? – ruief Aug 06 '17 at 07:01