我正在处理bash脚本,并且有一个curl cmd:
curl -u root:$pass -X PUT -H "Content-Type:application/json" http://$ip/nitro/ \
-d '{"user":{"username":"test","password":"test123" }}' -k
对于上述curl cmd中的密码test123,我想将其作为环境变量传递。尝试过以下方法,但无法正常工作。
curl -u root:$pass -X PUT -H "Content-Type:application/json" http://$ip/nitro/ \
-d '{"user":{"username":"test","password":$new_pswrd }}' -k
curl -u root:$pass -X PUT -H "Content-Type:application/json" http://$ip/nitro/ \
-d '{"user":{"username":"test","password":\"$new_pswrd\" }}' -k
[请在这里建议可能出什么问题,以及如何在curl cmd的后JSON参数中转义双引号?
您可以这样写:
[STEP 101] $ pass=test123
[STEP 102] $ echo '{"user":{"username":"test","password":"'"$pass"'" }}'
{"user":{"username":"test","password":"test123" }}
[STEP 103] $
((如果密码包含像"
这样的字符,这将不起作用。我不知道JSON的语法转义为"
和其他特殊字符,所以我不能再发表评论了。]
您使用单引号。 Bash允许两种不同的报价机制:
单引号:所有内容均为文字。双引号:解释$和\,将其余部分作为文字传递。
您的bash环境变量$ new_pswrd用单引号引起来,不会被扩展,但是将以美元符号和字母new_pswrd的形式传递。
有两种方法可以实现您的目标:
使用单引号:'将单引号'“结束,并将$ variable放在双引号中'',并且bash将连接所有字符串'”,因为它们在“”左引号和右引号“ _or_lack_white_space_entirely”之间缺少空格。 >
使用双引号:“当在\”双引号\“内时,反斜杠将被解释,反斜杠将导致以下字符(即使它是双引号)也将通过而不会关闭文字\”。美元符号将被扩展,而$ shell_variable将被其值替换,而\ $ shell_variable将不会。”