【发布时间】:2020-06-06 01:56:47
【问题描述】:
我有以下 bash 脚本,它使用其参数访问 RESTful Web 服务(通过 curl)并打印出 curl 请求和响应:
#! /bin/bash
# arguments:
# $1 - username
# $2 - password
#
# outputs:
# if the script exits with a non-zero status then something went wrong
# verify that we have all 6 required arguments and fail otherwise
if [ "$#" -ne 2 ]; then
echo "Required arguments not provided"
exit 1
fi
# set the script arguments to meaningful variable names
username=$1
password=$2
# login and fetch a valid auth token
req='curl -k -i -H "Content-Type: application/json" -X POST -d ''{"username":"$username","password":"$password"}'' https://somerepo.example.com/flimflam'
resp=$(curl -k -i -H "Content-Type: application/json" -X POST -d ''{"username":"$username","password":"$password"}'' https://somerepo.example.com/flimflam)
# echo the request for troubleshooting
echo "req = $req"
if [ -z "$resp" ]; then
echo "Login failed; unable to parse response"
exit 1
fi
echo "resp = $resp"
当我运行它时,我得到:
$ sh myscript.sh myUser 12345@45678
curl: (3) Port number ended with '"'
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0curl: (6) Could not resolve host: 12345@45678"
100 1107 100 1093 100 14 2849 36 --:--:-- --:--:-- --:--:-- 2849
req = curl -k -i -H "Content-Type: application/json" -X POST -d {"username":"$username","password":"$password"} https://somerepo.example.com/flimflam
resp = HTTP/1.1 400 Bad Request...(rest omitted for brevity)
显然,我没有正确地转义 curl 语句中的单引号和双引号的各个层,如以下输出所示:
curl: (6) Could not resolve host: 12345@45678"
和:
req = curl -k -i -H "Content-Type: application/json" -X POST -d {"username":"$username","password":"$password"} https://somerepo.example.com/flimflam
用户名/密码变量未解析的地方。
实际上,我的脚本需要的参数远不止 2 个,这就是为什么我将它们更改为具有有意义的变量名称(例如 $username 而不是 $1),以便它更易于理解和可读。
谁能看出我哪里出错了?提前致谢!
更新
我尝试了将req 变成:
curl -k -i -H 'Content-Type: application/json' -X POST -d "{'username':'myUser','password':'12345@45678'}" https://somerepo.example.com/flimflam
然而,这仍然是一个非法的 curl 命令,而是需要:
curl -k -i -H 'Content-Type: application/json' -X POST -d '{"username":"myUser","password":"12345@45678"}' https://somerepo.example.com/flimflam
【问题讨论】:
-
第一:不要尝试将命令存储在变量中; shell 在扩展变量之前解析引号,因此变量值中的引号没有任何用处。见BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!
-
啊,也许反过来(在命令本身中存储变量)?有趣的概念,虽然我很难看到实现中的“森林穿过树木”......