Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly escaping Json command line option in bash script

Tags:

bash

I have utility which accept JSON as argument. How to escape json correctly to pass to the utility? Example:

ip="127.0.0.1"
action='{\"server_ip\":\"$ip\",\"action\":\"stop\"}'
./fix-utility -e $action

But JSON is not getting escaped correctly.

like image 408
Vivek Goel Avatar asked Jan 14 '23 16:01

Vivek Goel


2 Answers

If you want interpolation of e.g. $ip inside the string, you need to use double quotes. Double quotes in the value need backslash escaping.

ip="127.0.0.1"
action="{\"server_ip\":\"$ip\",\"action\":\"stop\"}"
./fix-utility -e "$action"

Actually, I would advise against storing the action in a variable, unless your example omits something crucial which makes it necessary.

like image 174
tripleee Avatar answered Jan 20 '23 14:01

tripleee


Double quotes and single quotes is not considered same by bash interpreter: While double-quote let bash expand contained variables, single quote don't. Try simply:

echo "$BASH_VERSION"
4.1.5(1)-release
echo '$BASH_VERSION'
$BASH_VERSION

At all, there is a nice reusable bash way:

declare -A jsonVar
toJsonString() {
    local string='{'
    for var in ${!jsonVar[*]} ;do
        string+="\"$var\":\"${jsonVar[$var]}\","
      done
    echo ${string%,}"}"
}

jsonVar[action]=stop
jsonVar[server_ip]=127.0.1.2

toJsonString
{"action":"stop","server_ip":"127.0.1.2"}

And finally:

./fix-utility -e "$(toJsonString)"

This could be improved if specials chars like " double-quotes have to be part of some strings.

like image 36
F. Hauri Avatar answered Jan 20 '23 14:01

F. Hauri