在 Bash 中存储切片参数的最佳方式是什么?
What is the best way to store sliced arguments in Bash?
例子
>>./my_script.sh a b c
如果我尝试 echo
参数 2
- ...
,我可能会
>>echo "${@:2}"
a b c
如果我想将 ${@:2}
存储在变量中,这些方法将不起作用
my_params=${@:2}
或
my_params="${@:2}"
但这种方式可行
my_params="$(echo ${@:2})"
我能感觉到这种方式的丑陋。所以,我的问题是
存储切片参数的正确方法是什么?
如何将这些切片参数分配给变量?
如何再次作为另一个函数的参数重用?
在原版 Bourne shell 中,只有位置参数列表可用于此。幸运的是,现代衍生品有专门针对这种情况的数组变量类型。
array=("${@[2:]}") # note parentheses for array
echo "${array[0]}" # first arg of array
command "${array[@]}" # pass array as quoted arguments
例子
>>./my_script.sh a b c
如果我尝试 echo
参数 2
- ...
,我可能会
>>echo "${@:2}"
a b c
如果我想将 ${@:2}
存储在变量中,这些方法将不起作用
my_params=${@:2}
或
my_params="${@:2}"
但这种方式可行
my_params="$(echo ${@:2})"
我能感觉到这种方式的丑陋。所以,我的问题是
存储切片参数的正确方法是什么?
如何将这些切片参数分配给变量?
如何再次作为另一个函数的参数重用?
在原版 Bourne shell 中,只有位置参数列表可用于此。幸运的是,现代衍生品有专门针对这种情况的数组变量类型。
array=("${@[2:]}") # note parentheses for array
echo "${array[0]}" # first arg of array
command "${array[@]}" # pass array as quoted arguments