编辑脚本时会发生什么情况?

当一个脚本文件在运行时保存它,会发生什么事情,并会打印出我需要的结果。

我们来测试一下。

创建一个脚本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而异)。