0

I have a simple function in my bashrc file, it takes 2 arguments and makes a curl call. The problem is, the curl request is not getting the variable. Here's the function...

checkUserName() {
    cd ~/
    echo "checking for username $2"
    curl -w "@curl-format.txt" -H "Content-Type: application/json" -X POST -d '{"userName": "$2"}' http://localhost:8080/$1/verify
}
alias unameCheck=checkUserName

Then I call it with something like...

unameCheck users danwguy

and I will see...

checking for username danwguy

in my terminal prompt, however when I look at my logs from my application it shows that it is checking for userName $2 So the variable isn't being replaced in the curl command, even though the $1 is being replaced, since it is calling the correct API on my localhost. It replaces it in the echo command, but not in the curl command.

I have even tried creating a local variable, but that still doesn't work, no matter what I do, it doesn't replace in the curl call, but it does in the echo call. Can anyone see why it wouldn't be properly replacing the $2

Neglected Sanity
  • 1,770
  • 6
  • 23
  • 46

2 Answers2

3

Parameter expansions ($var) will not expand in single quotes. Use double quotes instead:

$ curl -w "@curl-format.txt" \
    -H "Content-Type: application/json" \
    -X POST \
    -d '{"userName": "'"$2"'"}' \
    "http://localhost:8080/$1/verify"

Also wrap parameter expansions in double quotes to avoid word splitting and pathname expansion.

Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
  • Good answer; terminology quibble: `$var` is a _reference to a parameter_ (variable). Recognizing that reference and replacing it with the parameter's value is what's called _parameter expansion_. Similarly, you avoid _unquoted references_ to parameters (or unquoted command substitutions / arithmetic expansions) to prevent word splitting and pathname expansion. – mklement0 Dec 01 '16 at 23:03
2

Just a note to previous comment.

You can escape double quotes with backslash, to tell bash interpreter to not interpret its special meaning, so final code looks like:

... -d "{\"userName\": \"$2\"}"  ...

Which is way more obvious for me...