在Bash中,如何访问函数内部的命令行参数?

我试图在bash中编写一个函数来访问脚本命令行参数,但是它们被replace为函数的位置参数。 如果函数没有明确的传入,有没有办法访问命令行参数?

# Demo function function stuff { echo $0 $* } # Echo's the name of the script, but no command line arguments stuff # Echo's everything I want, but trying to avoid stuff $* 

我阅读bash ref手册说这个东西是在BASH_ARGV中捕获的,虽然它谈论了很多“堆栈”。

 #!/bin/bash function argv { for a in ${BASH_ARGV[*]} ; do echo -n "$a " done echo } function f { echo f $1 $2 $3 echo -nf ; argv } function g { echo g $1 $2 $3 echo -ng; argv f } f boo bar baz g goo gar gaz 

保存在f.sh中

 $ ./f.sh arg0 arg1 arg2 f boo bar baz farg2 arg1 arg0 g goo gar gaz garg2 arg1 arg0 f farg2 arg1 arg0 

如果你想有你的参数C风格(参数数组+参数数量),你可以使用$ @和$#。

$#给你的参数个数。 $ @给你所有的参数。 你可以通过args=("$@")把它变成一个数组

举个例子:

 args=("$@") echo $# arguments passed echo ${args[0]} ${args[1]} ${args[2]} 

注意在这里${args[0]}实际上是第一个参数,而不是脚本的名字。

拉维的评论基本上是答案。 函数有自己的论点。 如果你希望它们和命令行参数一样,那么你必须把它们传入。否则,你显然是在调用没有参数的函数。

也就是说,如果你喜欢将命令行参数存储在全局数组中,以便在其他函数中使用:

 my_function() { echo "stored arguments:" for arg in "${commandline_args[@]}"; do echo " $arg" done } commandline_args=("$@") my_function 

你必须通过commandline_argsvariables访问命令行参数,而不是$@$1$2等,但是它们是可用的。 我不知道有任何方法直接分配给参数数组,但如果有人知道,请赐教!

另外,请注意我使用和引用$@ – 这是如何确保特殊字符(空白)不会被混淆。

 #!/usr/bin/env bash echo name of script is $0 echo first argument is $1 echo second argument is $2 echo seventeenth argument is $17 echo number of arguments is $# 

编辑:请看我对问题的评论

 # Save the script arguments SCRIPT_NAME=$0 ARG_1=$1 ARGS_ALL=$* function stuff { # use script args via the variables you saved # or the function args via $ echo $0 $* } # Call the function with arguments stuff 1 2 3 4 

也可以这样做

 #!/bin/bash # script_name function_test.sh function argument(){ for i in $@;do echo $i done; } argument $@ 

现在打电话给你的脚本

 ./function_test.sh argument1 argument2 

您可以使用shift关键字(运算符?)遍历它们。 例:

 #!/bin/bash function print() { while [ $# -gt 0 ] do echo $1; shift 1; done } print $*;