/ bin / bash和/ bin / sh之间的区别并直接调用脚本

时间:2012-12-26 07:28:03

标签: bash

这是我脚本的内容

#!/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

2 个答案:

答案 0 :(得分:1)

第一次使用/bin/bash test.sh运行此脚本时。第二次,您使用/bin/sh ./test.sh运行它。请注意差异:test.sh vs ./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并查看输出是否存在任何差异(不应该)。

答案 1 :(得分:1)

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

使用./test.sh运行时,路径名是相对的,不查询PATH,因此找到命令。

请注意/bin/bash ./test.sh会迭代,/bin/sh test.sh会失败;这不是/bin/bash/bin/sh之间差异的问题。