curl: füge in bash einen String als Option hinzu

1040
Andrew C

Ich möchte eine variable Zeichenfolge an Befehlsoptionen in curl übergeben.

if [ ! -z $ ]; then APISTRING+="--data-urlencode \"picture=$\" ";fi if [ ! -z $ ]; then APISTRING+="--data-urlencode \"additional_info="$"\" ";fi 

Wenn also Bild und Zusatz nicht leer sind, sollte $ APISTRING lauten:

--data-urlencode "picture=someinfo" --data-urlencode "additional_info=additional infos here" 

Aber wenn ich Curl anrufe

curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" "$" 

Es gibt einen Fehler wie

curl: Option --data-urlencode "picture = someinfo" --data-urlencode "additional_info = zusätzliche Infos hier": ist unbekannt

Hat jemand eine Idee, wie man damit umgehen soll?

0
Siehe [** Aber was ist wenn…? **] (https://unix.stackexchange.com/q/171346/23408#286350) Scott vor 6 Jahren 0
Siehe http://mywiki.wooledge.org/BashFAQ/050 glenn jackman vor 6 Jahren 0

2 Antworten auf die Frage

2
Gordon Davisson

Embedding quotes in a variable's value, like APISTRING+="--data-urlencode \"picture=$\" " does not work right. When you try to use $APISTRING, bash parses quotes before expanding the variable's value, and it doesn't rescan for "new" quotes after expansion. As a result, the quotes are treated as part of the string, rather than as delimiters around the string.

The best solution for things like this is to use an array to store the command options:

APISTRING=() if [ ! -z $ ]; then APISTRING+=(--data-urlencode "picture=$");fi if [ ! -z $ ]; then APISTRING+=(--data-urlencode "additional_info=$");fi curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" "$" 

Note that arrays are not available in all POSIX shells, so you should only use this in scripts you explicitly use bash for (i.e. a shebang of either #!/bin/bash or #!/usr/bin/env bash, not #!/bin/sh). Also, the syntax is very picky; don't leave off any of the parentheses in the assignments, the double-quotes, or the [@] when expanding the array.

BTW, there is another possible solution. Rather than accumulating the optional options beforehand, you can use conditional expansion to include them on the spot:

curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" \ $"} \ $"} 

Here, the :+ expansion tells bash to check whether the variable's nonblank, and if it is to not use it, but an alternate value: the quoted version of the variable with the appropriate prefix.

0
Sibilia

Sie haben in "$ " unnötige Anführungszeichen:

Fix:

curl -v -X "POST" --url "https://example.org/api" -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" $