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

查看:31
本文介绍了在 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 帖子很接近,但没有介绍如何创建数组:如何在 Bash 中解析命令行参数?

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 中特别有用,因为它没有任何其他像数组一样的东西.

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

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

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