I want to give a map-like structure as an argument to a bash script. I tried below methods, and they are working.
1. bash src.sh b:\{x:1,y:2}
2. bash src.sh b:'{x:1,y:2}'
"{}" also works
Above the first method somehow mess up when I use the command inside another script with possible line breaks inside the braces ( \\
).
bash src.sh b:\{x:1,\
y:2}
y:2} part is missing
The second method is somewhat fine but it contains the \\
inside the argument when the line break is inside quotes ''
bash src.sh b:'{x:1,\
y:2}'
argument will be b:{a:1,\ b:2}
Why can't I give {}
directly to a bash script? Is there a better way to do give {}
or completely new way to give a map-like structure as above.
Why can't I give
{}
directly to a bash script? Is there a better way to do give{}
or completely new way to give a map-like structure as above.
Neither {
nor }
is treated in a special way by bash when given as arguments to a command (unless you are unfortunate and happen to combine them to form a brace expansion or parameter expansion ). In your case, they are just plain characters in a string - but to avoid any future hazzle, consider surrounding the argument(s) with '
to avoid string interpolation.
Given this script:
for var in "$@"
do
echo ">$var<"
done
and this input
b:\{x:1,\
y:2}
you get this output
>b:{x:1,<
>y:2}<
The reason why the first part is in $1
and the second part is in $2
is because there are spaces in front of y
so the normal argument splitting comes into play. The newline does not matter in this case (it's not a part of the string). If you give this input instead:
b:\{x:1,\
y:2}
You'll get this output:
>b:{x:1,y:2}<
If you'd like to concatenate all the arguments into one, just use "$@"
:
var="$@" # or just var=$@
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.