Dea*_*all 18
(我知道这是一个老帖子,但没有一个答案真的回答了这个问题.)
使用BASH_ARGV数组.它包含以相反顺序传递给调用脚本的参数(即,它是顶部在索引0处的堆栈).您可能必须在shebang(例如,#!/bin/bash -O extdebug
)或shopt
(例如shopt -s extdebug
)中打开扩展调试,但它在bash 4.2_p37中对我有效而不打开它.
来自man bash
:
包含当前bash执行调用堆栈中所有参数的数组变量.最后一个子程序调用的最后一个参数位于堆栈的顶部; 初始调用的第一个参数位于底部.执行子程序时,提供的参数将被推送到BASH_ARGV.shell仅在处于扩展调试模式时才设置BASH_ARGV ....
这是我用来在一行上按顺序打印所有参数的函数:
# Print the arguments of the calling script, in order.
function get_script_args
{
# Get the number of arguments passed to this script.
# (The BASH_ARGV array does not include $0.)
local n=${#BASH_ARGV[@]}
if (( $n > 0 ))
then
# Get the last index of the args in BASH_ARGV.
local n_index=$(( $n - 1 ))
# Loop through the indexes from largest to smallest.
for i in $(seq ${n_index} -1 0)
do
# Print a space if necessary.
if (( $i < $n_index ))
then
echo -n ' '
fi
# Print the actual argument.
echo -n "${BASH_ARGV[$i]}"
done
# Print a newline.
echo
fi
}
Run Code Online (Sandbox Code Playgroud)
Caf*_*eur 12
正如Benoit所说,最简单的解决方案是将命令行参数作为函数参数传递给函数$@
,然后您可以以与函数外部完全相同的方式引用它们.您实际上将引用传递给函数的值,这些值碰巧与命令行参数具有相同的值,请记住这一点.
请注意,这几乎排除了您将任何其他参数传递给函数,除非您确切知道将在命令行传递多少个参数(不太可能由用户决定并且不受约束约束)
即
function fname {
# do something with $1 $2 $3...$n #
}
# $@ represents all the arguments passed at the command line #
fname $@
Run Code Online (Sandbox Code Playgroud)
更好的方法是仅传递您将要使用的参数,这样您就可以在函数中使用它们并且如果您愿意,还可以从代码中传递其他参数
即
function fname {
# do something with $1 $count $2 and $3 #
}
count=1
fname $1 $count $2 $3
Run Code Online (Sandbox Code Playgroud)
您可以将所有脚本参数存储在全局数组中:
args=("$@")
Run Code Online (Sandbox Code Playgroud)
然后在函数中访问它们:
f(){
echo ${args[0]} ${args[1]}
}
Run Code Online (Sandbox Code Playgroud)