0

I'm realy new to bash (coding at all) and i have a problem, which is probably realy simple to solve. I allready tried different versions of it, but it never gave me the correct result.

My goal is, that it use the curl command with the path of each subfolder. The problem is, in the curl command, it using "${d}" instead of the content of the variable. (tested with echo)

    for d in `find /some/path -mindepth 1 -type d`
do
    curl http://localhost:3456/api/command -X POST -d '{"name": "something", "path": "${d}"}' --header "X-Api-Key:myapikey"
done
wizzi
  • 23
  • 4

3 Answers3

0

The problem is that ${d} is surrounded by single quotes so it is not expanded. To see the difference try:

> d=5
> echo "${d}"
5
> echo '${d}'
${d}

So:

> d=5
> echo \"{\"name\": \"something\", \"path\": \"${d}\"}"
{"name": "something", "path": "5"}
builder-7000
  • 7,131
  • 3
  • 19
  • 43
0

On bash single quotes('') and double quotes("") have different meaning.I've tried without any quotes on variable and it works with echo. So it should work without echo also. Just wrap the -d flag with double quotes, inside it variable will be treated as variable not as a string.

#!/bin/bash
# GNU bash, version 4.3.46

for d in 1 2 3 4 5
do
    echo "curl http://localhost:3456/api/command -X POST -d "{'name': 'something', 'path': ${d}}" --header "X-Api-Key:myapikey""
done

If quote needed on dynamic variable,

 for d in "'1'" "'2'" "'3'" "'4'" "'5'"
do
    echo "curl http://localhost:3456/api/command -X POST -d "{'name': 'something', 'path': ${d}}" --header "X-Api-Key:myapikey""
done

DEMO: http://rextester.com/live/YAWHVN41557

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

Option 1

Write a function to get the object, this is usefull if you object has many parameters to interpolate.

get_data()
{
  cat <<EOF

 {"name": "something", 
  "path": "$d"
 } 
 EOF 
}

And then you use it

curl http://localhost:3456/api/command -X POST -d "$(get_data)" --header "X-Api-Key:myapikey"

Option 2

Close the single quotes and concatenate like this

'{"name": "something", "path": ' "$d" ' }'
jonhid
  • 2,075
  • 1
  • 11
  • 18
  • Thank you very much for your reply. I used option 2. The only problem was, that the content of $d was printed without "". The solution was to change it to "'"$d"'" – wizzi Apr 14 '18 at 14:14