如何将表达式的结果分配给bash中的变量
在以下bash脚本时,我试图将一个从JSON对象分配到变量的值。
#!/bin/bash
json_data='{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}'
echo json_data:
echo $json_data
echo country_code:
echo $json_data | jq '.country_code'
echo country_name:
echo $json_data | jq '.country_name'
cc=$json_data | jq '.country_code'
echo cc:
echo $cc
cn=$($json_data | jq '.country_name')
echo cn:
echo $cn
只是回应表达方式。 将表达式的值分配给变量CC或CN。
$ ./test.sh
json_data:
{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}
country_code:
"GB"
country_name:
"United Kingdom"
cc:
./test.sh: line 19: {"ip":"1.2.3.4",: command not found
cn:
$
我认为将表达式包装在$(...)中给出了我需要的功能,但这会导致错误。
谁能建议正确的语法?
In following bash script I'm trying to assign a value from a json object to a variable.
#!/bin/bash
json_data='{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}'
echo json_data:
echo $json_data
echo country_code:
echo $json_data | jq '.country_code'
echo country_name:
echo $json_data | jq '.country_name'
cc=$json_data | jq '.country_code'
echo cc:
echo $cc
cn=$($json_data | jq '.country_name')
echo cn:
echo $cn
Just echoing the expressions works.
Assigning the value of the expressions to variables cc or cn doesn't.
$ ./test.sh
json_data:
{"ip":"1.2.3.4", "country_code":"GB", "country_name":"United Kingdom"}
country_code:
"GB"
country_name:
"United Kingdom"
cc:
./test.sh: line 19: {"ip":"1.2.3.4",: command not found
cn:
$
I thought that wrapping an expression in $(...) gave the functionality I need, but that results in an error.
Could anyone advise as to the correct syntax?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您未包装的功能。包装全部表达式,包括
echo
。请记住引用变量扩展。使用ShellCheck检查您的脚本 - ShellCheck会通知您许多问题。
您可以将任何内容放入
$(...)
中,也许这将清除它:You did not wrap enough. Wrap the whole expression, including
echo
.Remember to quote variable expansions. Check your script with shellcheck - shellcheck will notify you of many problems.
You can put anything inside
$(...)
, maybe this will clear it: