2

Here is a bit of code I am having issues with

id=`my_api myrouter myroutername getsomething'{"uid":"$servername","meta_type":"system"}'| $SCRIPTS_DIR/jq -M '.result.data[].uid'`

for i in `echo $id`;
do

    echo $i
    echo ""
done

I am not able to pass the variable $servername inside backticks. Hardcoding the servername works absolutly fine

I am using a bash script. Tried escaping but it doesnt work. I know am missing something very trivial but it is not coming across to me.

Sash Sheen
  • 105
  • 2
  • 14
  • 2
    ```for i in `echo $id` ``` isn't generally good practice, by the way. Better to use `mapfile` or `read -a` to read your result into an array variable directly (rather than a string); that way you don't get unintended behavior such as glob expansion or string-splitting on undesired delimiters. – Charles Duffy Aug 09 '17 at 16:35
  • And variables should be passed to `jq` using `--arg`, not string substitution into JSON later parsed -- doing otherwise opens you up to injection attacks and malformed content (if the strings contain content that needs to be escaped). – Charles Duffy Aug 09 '17 at 16:36
  • 1
    And btw, your immediate problem is one that http://shellcheck.net/ will catch. – Charles Duffy Aug 09 '17 at 16:37
  • 2
    (Also, use `$()` rather than backticks -- both forms are POSIX-compliant, but backticks change the behavior of backslashes and other backticks in the command being run, making them prone to side effects and particularly hard to nest). – Charles Duffy Aug 09 '17 at 16:38
  • 1
    Thank you @CharlesDuffy for your feedback – Sash Sheen Aug 10 '17 at 07:19

1 Answers1

3

Backticks aren't the problem -- it's because the variable occurs within single quotes. Do this:

id=$(my_api myrouter myroutername getsomething'{"uid":"'"$servername"'","meta_type":"system"}'| $SCRIPTS_DIR/jq -M '.result.data[].uid')
# ............................................a........b^^^^^^^^^^^^^c.......................d

So, the single quoted string starts at "a", ends at "b", the variable is substituted within double quotes to extend the string, and then the rest of the single quoted string goes from "c" to "d"

glenn jackman
  • 238,783
  • 38
  • 220
  • 352