Monday, 1 July 2019

Bash and a sufficiency of input parameters

I hit an interesting quirk in Bash earlier today; I'm passing in a list of command-line parameters to a Bash script, using the $1, $2 etc. input parameter method.

However, I noticed that the TENTH parameter failed, and I ended up with a trailing zero on the end of a string that was actually the FIRST parameter.

It appeared that Bash was stopping at 9, and then simply adding the character '0' to the end of the string provided as the FIRST parameter.

Here's an example: -

#!/bin/bash

export A=$1
export B=$2
export C=$3
export D=$4
export E=$5
export F=$6
export G=$7
export H=$8
export I=$9
export J=$10

echo $J

When I execute the script: -

~/foo.sh 1 2 3 4 5 6 7 8 9 0

I'd expect to see this: -

The tenth parameter is 0

whereas I actually saw this: -

The tenth parameter is 10

As ever, the internet came to the rescue: -


which said, in part: -

...
Use curly braces to set them off:

echo "${10}"
...

I updated my script: -

#!/bin/bash

export A=${1}
export B=${2}
export C=${3}
export D=${4}
export E=${5}
export F=${6}
export G=${7}
export H=${8}
export I=${9}
export J=${10}

echo "The tenth parameter is" $J

and now it works as expected: -

The tenth parameter is 0

To be fair, the article also said: -

...
You can also iterate over the positional parameters like this:

for arg

or

for arg in "$@"

or

while (( $# > 0 ))    # or [ $# -gt 0 ]
do
    echo "$1"
    shift
done
...

which I should definitely try .........

No comments:

Just Announced - IBM Hyper Protect Virtual Servers

This is upon what my team and I have been working for the past few months, and I'm proud that we've announced it today: - IBM Hype...