0

这是我脚本的内容

#!/bin/bash
# test.sh
# Note: Set permissions on this script to 555 or 755,
# then call it with ./test.sh or sh ./test.sh.
echo
echo "This line appears ONCE in the script, yet it keeps echoing."
echo "The PID of this instance of the script is still $$."
# Demonstrates that a subshell is not forked off.
echo "==================== Hit Ctl-C to exit ===================="
sleep 1
exec $0 # Spawns another instance of this same script
#+ that replaces the previous one.
echo "This line will never echo!" # Why not?
exit 99 # Will not exit here!
# Exit code will not be 99!

这是我使用 /bin/bash 运行脚本时的输出

[user@localhost ~]$ /bin/bash test.sh 

This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4872.
==================== Hit Ctl-C to exit ====================
test.sh: line 11: exec: test.sh: not found

这是我使用 /bin/sh 运行脚本时的输出

[user@localhost ~]$ /bin/sh ./test.sh 

This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4934.
==================== Hit Ctl-C to exit ====================

This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4934.

==================== Hit Ctl-C to exit ====================

我不得不使用 Ctl-C 来阻止它。

为什么相同的脚本会根据不同的执行模式表现出不同的行为。仅供参考:我必须使用 Ctl-C 执行脚本,如下所示:./test.sh

4

2 回答 2

1

第一次使用/bin/bash test.sh. 第二次,您使用/bin/sh ./test.sh. 注意区别:test.shvs ./test.sh

无论出于何种原因,该脚本都无法生成运行该脚本的第二个进程,因为它无法找到test.sh. (我不确定这是为什么。我猜PATH可能是个问题?)请参阅以下错误消息:

[user@localhost ~]$ /bin/bash test.sh 

This line appears ONCE in the script, yet it keeps echoing.
The PID of this instance of the script is still 4872.
==================== Hit Ctl-C to exit ====================
test.sh: line 11: exec: test.sh: not found

脚本无法执行test.sh,因为它不知道在哪里test.sh./test.sh是脚本的完整路径,可以找到。

第二次运行时,子进程愉快地生成,因为./test.sh找到了。

尝试运行:/bin/bash ./test.sh/bin/sh ./test.sh查看输出是否有任何差异(不应该)。

于 2012-12-26T07:36:36.437 回答
1

您收到错误test.sh: not found是因为您的 PATH 中没有当前目录。

当您使用 运行它时./test.sh,路径名是相对的并且不参考 PATH,因此找到了该命令。

请注意,它/bin/bash ./test.sh会迭代,并且/bin/sh test.sh会失败;/bin/bash这不是和之间的区别问题/bin/sh

于 2012-12-26T07:38:06.357 回答