JChao JChao - 3 months ago 25
Bash Question

Shell script -- how to store curl command WITH variables result into another variable?

Currently I have a curl command that I want to store in a local variable. I know I could use `` or $() to get it done, but a variable inside the command stops me from doing so.

local sample_mapping="$(curl -XGET '${search_host}/${index}/_mapping')"


where search_host and index are two variables previously set. This command fails because
Couldn't resolve host '$search_host'


The other posts didn't talk about what to do when dealing with variables. Anyone has any idea?

Answer

This is the command in your command substitution:

curl -XGET '${search_host}/${index}/_mapping'

This command will not work on its own. The problem that you are observing is due to the single quotes, not to the use of command substitution, $(...).

Inside single-quotes, variables are not expanded. Since you need variable expansion, use double-quotes:

curl -XGET "${search_host}/${index}/_mapping"

Putting the above in your original command:

local sample_mapping="$(curl -XGET "${search_host}/${index}/_mapping")"

Note that quotes and command substitutions can nest : the fact that there are double quotes inside the command substitution has no effect on the double quotes outside of the command substitution.

Example

Let's define some variables:

$ search_host=http://google.com
$ index=index.html

Now, let's try the command with single-quotes:

$ a=$(curl -XGET '$search_host/$index')
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (6) Could not resolve host: $search_host

The above failed with an error message similar to the one you observed: Could not resolve host: $search_host

Let's try again with double-quotes:

$ a=$(curl -XGET "$search_host/$index")
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   229  100   

229 0 0 520 0 --:--:-- --:--:-- --:--:-- 521

The above succeeded.

Comments