命令替换,bash和管道出错

时间:2014-04-22 22:14:42

标签: linux bash command substitution

使用CentOS 6.4

执行:

var1=$(softnas-cmd checkupdate | jq .success)

给我一​​个错误:

"parse error: Invalid numeric literal at line 1, column 9"

如果我执行var1=$(softnas-cmd checkupdate)后跟echo $var1我得到:

{"success" : true, "session_id" : 1935, "result" : {"success":true,"msg":"You are running the latest version","records":{"version":"2.1.3.el6.x86_64","newversion":"2.1.3.el6.x86_64","updateavailable":false,"msg":"You are running the latest version"},"total":4}}

如果我然后执行var2=$(echo $var1 | jq .success)这是有效的,我得到了预期的: 真

最终我想这样做:

if [ $(softnas-cmd checkupdate | jq .succcess) = "true" ]; then
   echo "update required"
   ...
fi;

任何人都可以告诉我如何格式化命令替换,以便我可以一次执行吗?

由于

1 个答案:

答案 0 :(得分:0)

您是否尝试在字符串“updatevailable”之后解析true / false?如果是这样,试试这个:

res=`softnas-cmd checkupdate | sed -n "s/.*updateavailable\":\([tf][a-z]*\),.*/\1/p"`; 
if [ "$res" == "true" ]; then 
    echo "update required" ... 
fi;

但是,如果您尝试在第一个“成功”字符串后解析true / false,那么:

res=`softnas-cmd checkupdate | sed -n "s/.*\"success\" : \([tf][a-z]*\), .*/\1/p"`; 
if [ "$res" == "true" ]; then 
    echo "update required" ... 
fi;

并解析第二个“成功”字符串将是:

res=`softnas-cmd checkupdate | sed -n "s/.*\"success\":\([tf][a-z]*\), .*/\1/p"`; 
if [ "$res" == "true" ]; then 
    echo "update required" ... 
fi;