source
内部のコマンドが失敗した場合、dスクリプトを自動復帰させるにはどうすればよいですか?
たとえば、失敗時に自動終了するスクリプトがあるとしますset -e
。たとえば、
#!/bin/bash
# foo.env
set -e # auto-exit on any command failure
echo "hi"
grep 123 456 # this command will fail (I don't have a file named "456")
echo "should not reach here"
コマンドを正常に実行すると、失敗したgrep
コマンドで自動的に終了します。
box1% ./foo.env
hi
grep: 456: No such file or directory
ただし、source
スクリプトを実行すると、ソースとなるスクリプトだけでなく、現在のシェルが終了します。
box1% ssh box2
box2% source ./foo.env
hi
grep: 456: No such file or directory
Connection to box2 closed.
box1%
を削除するとset -e
、
#!/bin/bash
# foo2.env
echo "hi"
grep 123 456 # this command will fail (I don't have a file named "456")
echo "should not reach here"
次に、source
dスクリプトを自動で終了したり、自動で返したりしません。
box1% ssh box2
box2% source ./foo2.env
hi
grep: 456: No such file or directory
should not reach here
box2%
これまでに見つけた唯一の回避策return
は、スクリプト内のコードのすべての行に式を追加することです。
box1% cat foo3.env
#!/bin/bash
# foo3.env - works, but is cumbersome
echo "hi" || return
grep 123 456 || return
echo "should not reach here" || return
box1% source foo3.env
hi
grep: 456: No such file or directory
box1%
以下のための別の方法があるsource
Dスクリプトはどのように似て、set -e
非のために働くsource
Dのもの?
read
。