Bash, curl, eval and whitespace

I am writing a script to execute CURL commands for a given user input. The script has several helper functions for creating a list of parameters (arguments) that will ultimately be passed to CURL.

The above example is as follows:

#!/bin/bash
function create_arg_list
{
    # THIS HTTP HEADER VALUE COMES FROM THE USER and MAY CONTAIN SPACES
 local __hdr="x-madhurt-test:madh urt"
 local __params="http://google.co.in -X GET -H '$__hdr'"

 local __resultvar="$1"
 eval $__resultvar="\"$__params\""
 echo "params after eval : $__resultvar"
}


create_arg_list arg_list
echo "params after eval in main code : $arg_list"

echo "Running command : curl -v $arg_list"
curl -v $arg_list

The script works fine when the input parameters (file path, URL, etc.) have (quoted) spaces in them. However, when the arguments to be passed as HTTP headers in CURL contain spaces, the script fails.

Here is what I tried:

  • Use single quotes around the header value (for example, "$ __ hdr"). However, with this value, which is passed to CURL, is:
    curl -v http://google.co.in -X GET -H 'x- madhurt-test: madh urt'
    , CURL, , , :
    'x-madhurt-test:madh
  • (,\\ "$ __ hdr \\" ), , , . CURL "urt" URL
    curl: (6) Couldn't resolve host 'urt"'
  • (.. "madh\urt" "madh urt" ), , 2.

- , ?

+1
2

, . , , . , , . , Bash . , , , , . declare . .

#!/bin/bash
function create_arg_list
{
    # THIS HTTP HEADER VALUE COMES FROM THE USER and MAY CONTAIN SPACES
 local __hdr="x-madhurt-test:madh urt"
 local __params="http://google.co.in -X GET -H"
 __params=($__params "$__hdr")

 local __resultvar="$1"
 eval $__resultvar=$(printf "%q" "$(declare -p __params)")
 echo "params after eval : $__resultvar"
}

create_arg_list arg_list
echo "params after eval in main code : $arg_list"

echo "Running command : curl -v $arg_list"

eval $arg_list

curl -v "${__params[@]}"
+1

Dennis - , , . , , :

$ args() { for x in "$@"; do echo $x; done }
$ args 1 '2 b' 3
1
2 b
3

, , . , :

$ var="1 '2 b' 3"
$ args $var
1
'2
b'
3

Bash , ( ) . , , .

1: eval .

$ eval args $var
1
2 b
3

2: "$ {MYARRAY [@]}", .

: , , eval :

$ eval "$(create_args_list VARNAME)"

otherfun , VARNAME ( ). ( , ) . , , :

$ curl "${VARNAME[@]}"
+1

All Articles