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. 2 回目は、で実行し/bin/sh ./test.shます。違いに注意してtest.shください./test.sh

何らかの理由で、スクリプトはスクリプトを実行する 2 番目のプロセスを生成できません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検索可能なスクリプトへのフル パスです。

2 回目に実行すると、./test.shが見つかったため、子プロセスが正常に生成されます。

実行してみてください:/bin/bash ./test.shそして/bin/sh ./test.sh、出力に違いがあるかどうかを確認してください (違いはありません)。

于 2012-12-26T07:36:36.437 に答える
1

test.sh: not foundPATH に現在のディレクトリがないため、エラーが発生します。

で実行すると./test.sh、パス名は相対であり、PATH は参照されないため、コマンドが見つかります。

/bin/bash ./test.sh反復し、/bin/sh test.sh失敗することに注意してください。/bin/bashとの違いの問題ではありません/bin/sh

于 2012-12-26T07:38:06.357 に答える