bash 如果参数超过 9 个,如何访问函数的参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4816635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I access arguments to functions if there are more than 9 arguments?
提问by fzkl
With first 9 arguments being referred from $1-$9, $10 gets interpreted as $1 followed by a 0. How do I account for this and access arguments to functions greater than 10?
前 9 个参数从 $1-$9 引用,$10 被解释为 $1 后跟一个 0。我如何解释这一点并访问大于 10 的函数的参数?
Thanks.
谢谢。
回答by neuro
Use :
用 :
#!/bin/bash
echo
To test the difference with $10, code in foo.sh :
要测试 10 美元的差异,请在 foo.sh 中编写代码:
#!/bin/bash
echo
echo
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
我的2c
回答by Chl
If you are using bash, then you can use ${10}.
如果您使用的是 bash,那么您可以使用${10}.
${...} syntax seems to be POSIX-compliant in this particular case, but it might be preferable to use the command shiftlike that :
在这种特殊情况下,${...} 语法似乎符合 POSIX,但最好使用这样的命令shift:
while [ "$*" != "" ]; do echo "Arg: " shift done
EDIT: I noticed I didn't explain what shiftdoes. It just shift the arguments of the script (or function). Example:
编辑:我注意到我没有解释是什么shift。它只是改变脚本(或函数)的参数。例子:
> cat script.sh echo "" shift echo "" > ./script.sh "first arg" "second arg" first arg second arg
In case it can help, here is an example with getopt/shift :
如果它可以提供帮助,以下是 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=""
回答by l0b0
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}
通常,为了确保在 Bash 解释代码时将整个给定字符串用作变量名是安全的,您需要将其括在大括号中:${10}

