Bash脚本卷曲

时间:2018-02-02 06:12:09

标签: bash shell curl

#!/bin/bash

read -p 'Username: ' uservar
read -p 'Password: ' passvar

cacheVariable1="\"Content-Type:application/json"\"
cacheVariable2="\"Cache-Control:no-cache"\"
parametersVariable="'{\"username\":\"$uservar\",\"password\":\"$passvar\"}'"
echo $parametersVariable
echo $cacheVariable1 $cacheVariable2
websiteVariable="https://example.com/session"

echo $websiteVariable

entireURL="curl -X POST -H "$cacheVariable1" -H "$cacheVariable2" -d "$parametersVariable" "$websiteVariable""

echo "Entire URL IS: $entireURL"

result=`$entireURL`


echo "$result"

我希望我的脚本像这样:curl -X POST -H“Content-Type:application / json”-H“Cache-Control:no-cache”-d'{“username”:“abc@abc.com “,”“password”:“Password123”}'“https://example.com/session

整个网址IS:curl -H“Content-Type:application / json”-H“Cache-Control:no-cache”-d'{“username”:“zzzzzz”,“password”:“azzzsass”} 'https://cloud.tenable.com/session

但它不会在bash中执行。它给了我这个错误:

{"statusCode":400,"error":"Bad Request","message":"child \"username\" fails because [\"username\" is required]","validation":{"source":"payload","keys":["username"]}}

但它不起作用。任何人都可以帮助我吗?

更新

我自己解决了。一切都是正确的,除了执行eval $ wholeURL。 因为嵌套在括号内的命令作为子shell运行,所以我的环境变量丢失了。

1 个答案:

答案 0 :(得分:3)

#!/bin/bash

read -p 'Username: ' uservar
read -p 'Password: ' passvar

cacheVariable1="\"Content-Type:application/json"\"
cacheVariable2="\"Cache-Control:no-cache"\"
parametersVariable="'{\"username\":\"$uservar\",\"password\":\"$passvar\"}'"
echo $parametersVariable
echo $cacheVariable1 $cacheVariable2
websiteVariable="https://example.com/session"

echo $websiteVariable

entireURL="curl -X POST -H "$cacheVariable1" -H "$cacheVariable2" -d "$parametersVariable" "$websiteVariable""

echo "Entire URL IS: $entireURL"

result=`$entireURL`

eval $entireURL

这很完美!