我有一个简单的虚拟脚本test1
#!/bin/sh
echo "Starting ..."
. ./test2.sh
bring_data
this_is_it
echo "...Done"`
`
它调用另一个脚本(请注意,这里不是生成,而是获取)
#!/bin/sh
MY_DATA=\
"john road usa
adrian avenue nigeria
arthur street brazil
bill roads canada"
create_my_data() {
echo "name = ${1} type = ${2} country = ${3}"
if [ "${2}" = "avenue" ]; then
echo "failed... kick me out"
exit 2
fi
}
zombies_are() {
printf "%s" "${1}" | while read -r guy_name lives_on country; do
create_my_data "${guy_name}" "${lives_on}" "${country}"
done
}
bring_data() {
zombies_are "${MY_DATA}"
}
this_is_it() {
echo "... more work has to be done..."
sleep 1
echo "..."
}
由于test1.sh是test2.sh的来源...我希望调用exit 2会终止整个脚本调用。我希望调用that_is_it...不会发生...但它发生了。
这句台词有什么特别的地方吗:while read -r guy_name lives_on country; do
'不允许完全退出调用test1.sh???
以下是此时的输出:
# ./test1.sh
Starting ...
name = john type = road country = usa
name = adrian type = avenue country = nigeria
failed... kick me out
... more work has to be done...
...
...Done
我把密码改成了...
'僵尸_是“${MY_DATA}”||出口2 ′
现在起作用了。
2条答案
按热度按时间wn9m85ua1#
我将代码更改为:
bring_data() { zombies_are "${MY_DATA}" || exit 2 }
vx6bjr1n2#
The
while
loop is spawned in another subshell due to the pipe (|
)。exit
命令退出此子shell。您可以使用以下最小脚本尝试执行此操作:sh -c 'exit; echo hi'
,相对于sh -c ': | exit; echo hi'
的变化。一个解决方案是使用process substitution,以将while循环保留在同一个shell中: