bash帮助在while循环中使用EOF
问题描述:
我有一个脚本,它逐行读取一些输入信息,然后进入循环,然后在内部循环中,它创建带有一些基于信息的扩展变量的json文件从不同的输入信息中获取信息。bash帮助在while循环中使用EOF
问题是,当我使用cat & EOF时,它打破了while循环,并且只从输入信息中读取第一行。 你能不能指点如何改写脚本,以不打破while循环与EOF功能:
while IFS= read -r snmp_cred; do
echo appliance $ADDM_address and $snmp_cred
snmp_ip=$(grep -E -o "([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})@" <<< $snmp_cred)
snmp_ip=${snmp_ip%?}
echo IP for snmp community is $snmp_ip
json_file=$DIR/cred.json
remote_dir=/some/remote/dir
cat <<EOF > $DIR/cred.json
{
"some",
"json,
}
EOF
[Here goes some another commands]
done <$DIR/input.txt
答
的代码看起来不错,但你可以尽量避免使用cat
干脆在这里。只需使用echo
或printf
即可。
printf '\
{
"ip_range" : "%s",
"types" : [ "snmp" ],
"description" : "%s",
"snmp.version": "v2c",
"snmp.port" : 161,
"snmp.community" : "%s",
"snmp.retries" : 3,
"snmp.timeout" : 2 }' "$snmp_ip" "$snmp_cred" "$snmp_cred" > "$json_file"
一般而言,一旦你想生成动态JSON,你不用担心的参数值进行正确编码。在这种情况下,您可能需要考虑使用诸如jq
之类的工具来生成JSON,而不是手动构建它。
jq -n --arg ipr "$ip_range" --arg cred "$snmp_cred" '{
"ip_range" : $ipr,
"types" : [ "snmp" ],
"description" : $cred,
"snmp.version": "v2c",
"snmp.port" : 161,
"snmp.community" : $cred,
"snmp.retries" : 3,
"snmp.timeout" : 2 }' > "$json_file"
的问题是,在JSON文件我有一些变量,它们不膨胀,当我用你的方法: –
这里是JSON代码 - \t \t { \t \t \t “IP_RANGE”:“$ snmp_ip ”, \t \t \t “类型”:[ “SNMP”], \t \t \t “描述”: “$ snmp_cred”, \t \t \t “snmp.version”: “V2C” \t \t \t “snmp.port”:161, \t \t \t “snmp.community”: “$ snmp_cred”, \t \t \t “snmp.retries”:3, \t \t \t “snmp.timeout”:2 \t \t} –
好的,当我使用jq时,它给我编译错误: –