问题描述
如何转换命令行参数为一个bash脚本阵列?
我想借此:
./ something.sh ARG1参数3
和将其转换成
myArray的=(ARG1参数3)
这样我可以用myArray的为脚本中进一步使用。
这previous SO后接近,但不会进入如何创建数组:的
我需要的参数转换为常规bash脚本数组;我知道我可以使用其他语言(Python的,例如),但需要这样做在bash。我想我正在寻找一个追加功能或类似的东西?
更新:我也想问如何检查零参数和分配一个默认数组值,并感谢下面的答案,能得到这个工作:
如果[$#-eq 0];然后
myArray的=(defaultarg1 defaultarg2)
其他
myArray的=($ @)
科幻
其实您的命令行参数的实际的像一个数组了。至少,你可以把在 $ @
变量很像一个数组。这就是说,你可以将其转换成这样一个实际的数组:
myArray的=($ @)
如果你只是想输入一些参数并将其送入 $ @
值,使用设置
:
$集 - 苹果香蕉猕猴桃
$回声$#
3
$回声$ @
苹果香蕉猕猴桃
了解如何使用参数结构是POSIX SH,其中有没有别的喜欢的数组中特别有用。
How do I convert command-line arguments into a bash script array?
I want to take this:
./something.sh arg1 arg2 arg3
and convert it to
myArray=( arg1 arg2 arg3 )
so that I can use myArray for further use in the script.
This previous SO post comes close, but doesn't go into how to create an array: How do I parse command line arguments in bash?
I need to convert the arguments into a regular bash script array; I realize I could use other languages (Python, for instance) but need to do this in bash. I guess I'm looking for an "append" function or something similar?
UPDATE: I also wanted to ask how to check for zero arguments and assign a default array value, and thanks to the answer below, was able to get this working:
if [ "$#" -eq 0 ]; then
myArray=( defaultarg1 defaultarg2 )
else
myArray=( "$@" )
fi
Actually your command line arguments are practically like an array already. At least, you can treat the $@
variable much like an array. That said, you can convert it into an actual array like this:
myArray=( "$@" )
If you just want to type some arguments and feed them into the $@
value, use set
:
$ set -- apple banana "kiwi fruit"
$ echo "$#"
3
$ echo "$@"
apple banana kiwi fruit
Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.
这篇关于击:convert命令行参数到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!