Using Environment Variables in cURL Command - Unix

2020-07-09 02:49发布

My question is very simple. I want to use environment variables in a cURL command sth similar to this:

curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"$USERNAME","password":"$PASSWORD"}' 

When I run the command $USERNAME is passed to the command as a "$USERNAME" string not the value of the variable. Is there a way to escape this situation?

Thanks.

4条回答
可以哭但决不认输i
2楼-- · 2020-07-09 02:52
curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"'$USERNAME'","password":"'$PASSWORD'"}'

Here the variable are placed outside of "'" quotes and will be expanded by shell (just like in echo $USERNAME). For example assuming that USRNAME=xxx and PASSWORD=yyy the argv[7] string passed to curl is {"username":"xxx","password":"yyy"}

And yes, this will not work when $USERNAME or $PASSWORD contain space characters.

查看更多
啃猪蹄的小仙女
3楼-- · 2020-07-09 03:05

Our: curl -k -X POST -H 'Content-Type: application/json' -d '{"username":"'"$USERNAME"'","password":"'"$PASSWORD"'"}'

查看更多
Viruses.
4楼-- · 2020-07-09 03:10

Single quotes inhibit variable substitution, so use double quotes. The inner double quotes must then be escaped.

...  -d "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD\"}"
查看更多
姐就是有狂的资本
5楼-- · 2020-07-09 03:16

For less quoting, read from standard input instead.

curl -k -X POST -H 'Content-Type: application/json' -d @- <<EOF
{ "username": "$USERNAME", "password": "$PASSWORD"}
EOF

-d @foo reads from a file named foo. If you use - as the file name, it reads from standard input. Here, standard input is supplied from a here document, which is treated as a double-quoted string without actually enclosing it in double quotes.

查看更多
登录 后发表回答