Wednesday, December 12, 2012

Messing up with command-line arguments in Bash: $*, $@, "$*", "$@",…

Figured out a stupid issue that plagued a bit of code I had for quite a while.  Didn't care about it enough to google it till recently tho.

Quoting the source:
It’s stupid, but it took me a good hour to figure this out, so maybe I’m not the only one…
I’ve recently had a problem with command-line arguments in my Java program. The problem was that command line arguments containing spaces were parsed incorrectly, i.e. chopped into individual arguments. My initial suspect was gnu.Getopt package I use for parsing arguments, but as it turned out I was wrong.
The real culprit was a shell wrapper script I used to wrap my java code. The code was the following:

java -some parameters- -programm .class- $@
 
See the problem? I didn’t. You need quotes around "$@" in which case the parameter gets expanded to: "$1" "$2" "$3"... With no quotes the shell expands it to $1 $2 $3, hence all parameters containing spaces get chopped (also globbing takes place in this case).
BTW: There’s also "$*" which is used to combine all parameters into a single one, i.e, "$*" expands to "$1c$2c$3c..., where c is $IFS (or space). Here it’s also important to have it enclosed in quotes.