【发布时间】:2017-10-11 01:09:37
【问题描述】:
我有一个如下所示的 curl 命令:
curl -X PUT -H "myheader:coca-cola" -d '{ "name":"harrypotter" }' http://mygoogle.com/service/books/123
通过终端按原样运行此命令会返回预期结果。
我正在尝试将此 curl 命令合并到我的 bash 脚本中,如下所示:
#!/bin/bash
MYURL=http://mygoogle.com/service/books/123
# Generate body for curl request
generate_put_data()
{
cat <<EOF
{
"name":"harrypotter"
}
EOF
}
put_data=$(echo "$(generate_put_data)")
put_data_with_single_quotes="'$put_data'"
# Generate headers for curl request
header=myheader:coca-cola
header_with_double_quotes="\"$header\""
# The following function takes two inputs - a simple string variable (with no spaces or quotes) and the curl command string
function run_cmd() {
echo $1
echo $2
#Run the curl command
"$2"
#Check return code of the curl command
if [ "$?" -ne 0 ]; then
#do something with simple string variable
echo "$1"
echo "Job failed"
exit 1
else
#do something with simple string variable
echo "$1"
echo "Job Succeeded"
fi
}
# Run the bash function - run_cmd
run_cmd "mysimplestring" "curl -X PUT -H $header_with_double_quotes -d $put_data_with_single_quotes $MYURL"
但是,当我尝试运行上述 bash 脚本时,它会在我使用两个输入调用 run_cmd() 函数时失败。我收到以下错误:
curl -X PUT -H "myheader:coca-cola" -d '{
"name":"harrypotter"
}' http://mygoogle.com/service/books/123: No such file or directory
Job failed
此错误发生在 run_cmd() 函数声明中正在执行 "$2" 的行。
有人可以帮助我了解我哪里出错了吗?谢谢!
【问题讨论】:
-
在变量中嵌入引号不起作用。变量包含数据;在 shell 语法中,引号围绕 数据,而不是 in 数据。请参阅我对this question on superuser 的回复。
标签: bash shell curl double-quotes single-quotes