【问题标题】:Curl command in bash script using variablesbash脚本中使用变量的curl命令
【发布时间】: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


【解决方案1】:
"$2"

这将采用第二个参数并尝试在不进行任何分词的情况下运行它。它把它当作一个字符串。

您将在将 curl 命令作为一个字符串传递时遇到问题。如果你不带引号传递它,你会做得更好,就像你在命令行上键入它一样。您需要引用每个变量,但不要引用整个命令。

run_cmd "mysimplestring" curl -X PUT -H "$header" -d "$put_data" "$MYURL"

请注意,您不再需要“with_quotes”变量。你不必做那样的事情。原始的普通值将起作用。

现在您可以使用数组语法访问命令:

function run_cmd() {
  local name=$1; shift
  local cmd=("$@")

  #Run the curl command
  "${cmd[@]}"
}

顺便说一句,这是echo的无用用法:

put_data=$(echo "$(generate_put_data)")

做到这一点:

put_data=$(generate_put_data)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    • 2020-04-30
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多