curl outfile 变量在 bash 脚本中不起作用

Cha*_*ase 4 bash shell-script curl

尝试缩短使用 curl 获取多个 API 调用的 bash 脚本需要如下操作:

curl --user $USER:$PASS https://api.example.com/foo -o 'foo.json'
curl --user $USER:$PASS https://api.example.com/bar -o 'bar.json'
curl --user $USER:$PASS https://api.example.com/baz -o 'baz.json'
Run Code Online (Sandbox Code Playgroud)

并以这种形式使用它:

curl --user $USER:$PASS https://api.example.com/{foo,bar,baz} -o '#1.json'
Run Code Online (Sandbox Code Playgroud)

问题是 curl 正在获取 foo、bar 和 baz,但没有将输出分配给 foo.json、bar.json 和 baz.json。它实际上是在创建 #1.json 并将输出管道传输到 stdout。已尝试使用单引号、双引号和无引号,结果都是一样的。这是在 bash 脚本中运行的,尽管 curl 命令在直接在命令行上输入时的行为方式相同。这是 OS X 语法问题吗?

lar*_*sks 11

您的问题是该{...}表达式也是有效的 shell 语法。例如,运行:

echo file/{one,two}
Run Code Online (Sandbox Code Playgroud)

你会得到:

file/one file/two
Run Code Online (Sandbox Code Playgroud)

所以当你运行时:

curl --user $USER:$PASS https://api.example.com/{foo,bar,baz} -o '#1.json'
Run Code Online (Sandbox Code Playgroud)

{foo,bar,baz}是越来越贵解释外壳,和curl实际收到命令行:

  curl --user youruser:secret https://api.example.com/foo https://api.example.com/bar https://api.example.com/baz -o '#1.json'
Run Code Online (Sandbox Code Playgroud)

由于curl没有看到{...}表达式,因此您无法获得#1. 解决方案只是将 URL 用单引号括起来:

curl --user $USER:$PASS 'https://api.example.com/{foo,bar,baz}' -o '#1.json'
Run Code Online (Sandbox Code Playgroud)

单引号禁止字符串的任何外壳扩展。