bash 帮助在 while 循环中使用 EOF
bash help using EOF inside a while loop
我有一个脚本,它逐行读取一些输入信息,然后进入循环,然后在循环内部,它根据从中获取的信息创建带有一些扩展变量的文件 json输入信息,时时不同。
问题是,当我使用 cat & EOF 时,它会中断 while 循环并仅从输入信息中读取第一行。
您能否建议如何重写脚本以不使用 EOF 函数中断 while 循环:
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输入信息,时时不同。
问题是,当我使用 cat & EOF 时,它会中断 while 循环并仅从输入信息中读取第一行。 您能否建议如何重写脚本以不使用 EOF 函数中断 while 循环:
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"