在shell脚本中使用curl替换变量

3

你好,我正在尝试在shell脚本中使用curl,如下所示,但是我无法将变量$line替换到CURL中。请建议。

while read line
do
    echo "allowing mac $line"
    curl -X POST -d '{"src-mac": "$line"}' http://localhost:8080/wm/firewall/rules/json
    curl -X POST -d '{"dst-mac": "$line"}' http://localhost:8080/wm/firewall/rules/json
done < /home/floodlight/allowedmacs
1个回答

7

在单引号中无法进行变量替换。请使用双引号来扩展变量,例如:

curl -X POST -d '{"src-mac": "'"$line"'"}' http://localhost:8080/wm/firewall/rules/json
curl -X POST -d '{"dst-mac": "'"$line"'"}' http://localhost:8080/wm/firewall/rules/json

或者您可以在整个内容周围使用双引号,并转义内部引号:

curl -X POST -d "{\"src-mac\": \"$line\"}" http://localhost:8080/wm/firewall/rules/json
curl -X POST -d "{\"dst-mac\": \"$line\"}" http://localhost:8080/wm/firewall/rules/json

无论哪种情况,如果你想要展开它,当你到达$line时,它不能在单引号内。

"{'src-mac': '$line'}" 请将双引号和单引号互换。 - glenn jackman
1
@glennjackman - 不行。虽然在JavaScript代码中是有效的文字,但在要求字符串周围有双引号的JSON中是不合法的。 - Mark Reed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接