exit
调用错误时不会终止脚本。
Error: Could not resolve localhost
after exit
#!/bin/sh
resolve_ip (){
if [ -z "$1" ]; then
host="localhost"
ip=$(dig +short myip.opendns.com @resolver1.opendns.com)
else
host="$1"
ip=$(dig +short $1)
fi
if [ -z "$ip" ]; then
error "Could not resolve $host"
fi
echo "$ip"
}
error (){
(>&2 echo "Error: $1")
exit 1
}
master_host='google.com'
if [ "$(resolve_ip)" = "$(resolve_ip $master_host)" ]; then
error "some error"
fi
echo "after exit"
exit
exit
退出当前的shell进程¹。
在中$(resolve_ip)
,它resolve_ip
是在subshell进程中运行。
你可以做:
my_ip=$(resolve_ip) || exit
master_ip=$(resolve_ip "$hostname") || exit
if [ "$my_ip" = "$master_ip" ]; ...
当子shell以非零退出状态退出时,使主shell退出(具有与子shell相同的退出代码)。
同样,就像resolve_ip
在子shell环境中运行一样,$ip
and$host
变量在该子shell返回后将无法生存。
还要注意,(...)
in(>&2 echo "Error: $1")
还启动了一个子shell。除非您想解决stderr是坏管道的情况,否则在这里并没有必要,并且如果写入错误消息将导致SIGPIPE传递到echo
内置的主shell进程中。
在这里,您可以通过将其存储在用户提供的变量中来返回输出,而不是通过stdout返回输出:
resolve_ip (){ # args: ip_var [host]
if [ "$#" -eq 1 ]; then
host=localhost
eval "$1="'$(dig +short myip.opendns.com @resolver1.opendns.com)'
else
host=$2
eval "$1="'$(dig +short "$2")'
fi
if eval '[ -z "${'"$1"'}" ]'; then
error "Could not resolve $host"
fi
}
# ...
resolve_ip my_ip
resolve_ip master_ip "$hostname"
if [ "$my_ip" = "$master_ip" ]; ...
¹严格来说,子外壳环境不必使用子进程来实现,有些外壳诸如此类ksh93
并不是为了优化,但仍然exit
仅存在子外壳,而不是主外壳。ksh93
但是具有${ ...; }
不涉及子shell环境的形式或命令替换,因此exit
将退出主shell。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句