Bash脚本问题:SSH远程获取的变量无法被if语句识别
问题描述
通过SSH远程执行systemctl命令获取服务状态并赋值给变量devstate1,用printf输出该变量时显示为failed,符合预期,但if语句无法正确识别该值,无法将变量devstate2设置为Stopped。尝试两种if写法均无效,但判断变量值为active的类似语句可正常运行。
问题代码片段1
devstate1=`ssh root@10.1.1.1 systemctl status application | grep Active | cut -c 12- | cut -c -7` devstate2=0 if [ "$devstate1" == "failed" ] then devstate2=Stopped fi printf $devstate2\n
问题代码片段2(尝试过的写法)
if [[ devstate1 == "failed" ]] then devstate2=Stopped fi
可正常运行的代码
if [ "$devstate1" == "active" ] || [ "$devstate2" == "active" ] then echo Aborted! Dev Service still active exit 1 fi if [ "$stagestate1" == "active" ] || [ "$stagestate2" == "active" ] then echo Aborted! Stage Service still active exit 1 fi
原因分析
核心问题是手动按字符截取的devstate1可能包含不可见空白字符(空格、换行等)。systemctl status的Active行格式类似Active: failed (Result: exit-code) ...,用cut -c 12- | cut -c -7截取时,failed后面会带一个空格,导致变量实际值是failed (带空格),和纯字符串"failed"不匹配。而active的位置刚好是7个字符且无后续空格,所以判断逻辑能生效。
解决方案
方案1:用awk精准提取状态值
抛弃手动按位截取,改用awk直接提取Active:后的第一个字段,结果更可靠:
devstate1=$(ssh root@10.1.1.1 systemctl status application | awk '/Active:/ {print $2}') devstate2=0 if [ "$devstate1" = "failed" ]; then devstate2=Stopped fi printf "%s\n" "$devstate2"
方案2:清理变量中的空白字符
如果坚持原截取逻辑,可通过tr删除所有空白字符:
devstate1=$(ssh root@10.1.1.1 systemctl status application | grep Active | cut -c 12- | cut -c -7 | tr -d '[:space:]')
方案3:使用模式匹配忽略尾部空格
用[[的模式匹配功能,允许failed后面带任意字符:
if [[ "$devstate1" == "failed"* ]]; then devstate2=Stopped fi
内容的提问来源于stack exchange,提问作者Chris Surman
相关产品推荐
相关产品推荐

