☑ Bash expansion weirdness

25 Jan 2013 at 11:12AM in Software
 | 
Photo by Vicko Mozara
 | 

Expanding a substring of “$*” in bash seems to magically add command-line parameter zero.

inflatable flamingo

Here’s a quirky one. In the bash shell, "$*" expands to a single string which is a whitespace-separated list of arguments starting at one. So if you have the following script as script.sh:

1
2
#!/bin/bash
echo Arguments: "$*"

… and you call it as script.sh arg1 arg2 arg3 then you’ll get the following output:

Arguments: arg1 arg2 arg3

So far so tedious. However, if we use some of bash’s parameter expansion rules to select a substring (in this case the substring starting at zero, or the whole string in fact):

1
2
#!/bin/bash
echo Arguments: "${*:0}"

… then suddenly you get parameter zero (the filename of the script) included:

Arguments: ./script.sh arg1 arg2 arg3

I’m not sure if that’s a bug or I’m missing some subtlety and it’s expected behaviour, but it’s one of those issues that’s pretty tough to Google around so I suspect it’ll remain a mystery.

25 Jan 2013 at 11:12AM in Software
 | 
Photo by Vicko Mozara
 |