当脚本文件仍然运行时,会发生什么,并且会打印出我需要的结果.
解决方法
我们来测试一下
创建脚本test.sh:
#!/usr/bin/env bash sleep 1 echo 'echo "executed overwritten"' >> "$0" # append to self sleep 1 echo 'executed original'
并执行它:
$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 $
请注意,bash继续阅读修改后的文件.当文件更改时,它会保留其文件中的当前位置(以字节为单位).
作为示范,脚本
#!/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'
给出输出
$./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'
请注意,它试图执行随机乱码.
(这是Ubuntu 12.04.行为可能因其他shell而异)