bash – 在变量上保存命令输出并检查退出状态
发布时间:2020-12-15 21:55:17 所属栏目:安全 来源:网络整理
导读:以下命令将解析google ip ip=`dig +short google.com` echo $ip 216.58.210.238 有时(特别是当互联网连接丢失时)此命令失败并显示此错误 ;; connection timed out; no servers could be reached 当命令失败并且我使用$#时,分配的输出为0 ip=`dig +short goog
以下命令将解析google ip
> ip=`dig +short google.com` > echo $ip > 216.58.210.238 有时(特别是当互联网连接丢失时)此命令失败并显示此错误 > ;; connection timed out; no servers could be reached 当命令失败并且我使用$#时,分配的输出为0 > ip=`dig +short google.com` > echo $# > 0 > echo $ip # Command failed > ;; connection timed out; no servers could be reached 如何在变量中保存命令输出,同时检查命令是否成功 解决方法
你应该使用$?而不是$#.
$? - contains the return value from the last script. $# - contains the total number of arguments passed to a script or function 做类似下面的事情: if $? then echo "Success" # Do something here else echo "Fail" # Fallback mode fi 编辑:回复this评论回答标题中的问题:
正如0700在this评论中指出的那样,赋值不会干涉命令的退出状态.所以: ip=$(dig +short google.com) # Just changed the legacy backticks to $() [ $? -eq 0 ] && echo "dig succeeded" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |