☑ Bash expansion weirdness

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:

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):

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 by Andy Pearce in Software  | Photo by Vicko Mozara  | Tags: linux bash  |  See comments

⇐ Page 1   |   ← Page 15   |   Page 16 of 16