How do I access arguments to functions if there are more than 9 arguments?
With first 9 arguments being referred from $1-$9, $10 gets i开发者_StackOverflow中文版nterpreted as $1 followed by a 0. How do I account for this and access arguments to functions greater than 10?
Thanks.
Use :
#!/bin/bash
echo ${10}
To test the difference with $10, code in foo.sh :
#!/bin/bash
echo $10
echo ${10}
Then :
$ ./foo.sh first 2 3 4 5 6 7 8 9 10
first0
10
the same thing is true if you have :
foobar=42
foo=FOO
echo $foobar # echoes 42
echo ${foo}bar # echoes FOObar
Use {}
when you want to remove ambiguities ...
my2c
If you are using bash, then you can use ${10}
.
${...} syntax seems to be POSIX-compliant in this particular case, but it might be preferable to use the command shift
like that :
while [ "$*" != "" ]; do echo "Arg: $1" shift done
EDIT: I noticed I didn't explain what shift
does. It just shift the arguments of the script (or function). Example:
> cat script.sh echo "$1" shift echo "$1" > ./script.sh "first arg" "second arg" first arg second arg
In case it can help, here is an example with getopt/shift :
while getopts a:bc OPT; do case "$OPT" in 'a') ADD=1 ADD_OPT="$OPTARG" ;; 'b') BULK=1 ;; 'c') CHECK=1 ;; esac done shift $( expr $OPTIND - 1 ) FILE="$1"
In general, to be safe that the whole of a given string is used for the variable name when Bash is interpreting the code, you need to enclose it in braces: ${10}
精彩评论