将命令行参数转换为Bash中的数组 [英] Convert command line arguments into an array in Bash

查看:120
本文介绍了将命令行参数转换为Bash中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将命令行参数转换为bash脚本数组?

How do I convert command-line arguments into a bash script array?

我想吃这个:

./something.sh arg1 arg2 arg3

并将其转换为

myArray=( arg1 arg2 arg3 )

以便我可以在脚本中使用myArray进行进一步的使用.

so that I can use myArray for further use in the script.

上一条SO帖子即将结束,但没有涉及如何创建数组:

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?

我需要将参数转换为常规的bash脚本数组;我意识到我可以使用其他语言(例如Python),但是需要在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=( "$@" )

如果只想键入一些参数并将其输入$@值,请使用set:

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

了解如何使用参数结构在POSIX sh中特别有用,因为POSIX sh没有像数组那样的东西.

Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.

这篇关于将命令行参数转换为Bash中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆