Search code examples
bashquoting

how to use hostname variable in single quoted?


In the bash file named "input_data"

LA=$1
curl -H 'Content-Type: application/x-ndjson' -XPOST '"'$LA'":9200/human_flow/human_flow/_bulk?pretty' --data-binary @$2.json

When running command

 ./input_data localhost human_flow

give error message

bash-3.2$ ./input_data localhost human_flow
curl: (6) Could not resolve host: "localhost"

localhost can be resolved

bash-3.2$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.067 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.156 ms

use 127.0.0.1 instead of localhost

bash-3.2$ ./input_data 127.0.0.1 human_flow
curl: (6) Could not resolve host: "127.0.0.1"

Solution

  • Correct usage would look like:

    curl \
      -H 'Content-Type: application/x-ndjson' \
      -XPOST \
      --data-binary "@$2.json" \
      "$LA:9200/human_flow/human_flow/_bulk?pretty"
    
    • All expansions are in double quotes -- neither in single quotes (which prevents them from being expanded) nor unquoted.
    • Double quotes must not be inside single quotes if they are expected to have semantic meaning.
    • By POSIX convention, positional arguments should be specified after all optional arguments. Applications following GNU conventions don't strictly require this, but following it across-the-board avoids surprises.