linux shell 是否支持列表数据结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12316167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:17:18  来源:igfitidea点击:

does linux shell support list data structure?

linuxbashshellash

提问by hugemeow

this question is not the same as Does the shell support sets?

这个问题和Does the shell support sets不一样

i know lots of script language support list structure, such as python, python, ruby, and javascript, so what about linux shell?

我知道很多脚本语言支持列表结构,比如python、python、ruby和javascript,那么linux shell呢?

does shell support such syntax?

shell 支持这样的语法吗?

for i in list:
do
     print i
done

i would first to initialize a list, for example:

我会首先初始化一个列表,例如:

ListName = [ item1, item2, ..., itemn ]

then iterate over it

然后迭代它

is that possible when programming shell scripts?

编程shell脚本时可能吗?

采纳答案by chepner

It supports lists, but not as a separate data structure (ignoring arrays for the moment).

它支持列表,但不作为单独的数据结构(暂时忽略数组)。

The forloop iterates over a list (in the generic sense) of white-space separated values, regardless of how that list is created, whether literally:

for白色空间在列表循环迭代(一般意义上的)分隔值,不管如何被创建的列表,无论是从字面上:

for i in 1 2 3; do
    echo "$i"
done

or via parameter expansion:

或通过参数扩展:

listVar="1 2 3"
for i in $listVar; do
    echo "$i"
done

or command substitution:

或命令替换:

for i in $(echo 1; echo 2; echo 3); do
    echo "$i"
done

An array is just a special parameter which can contain a more structured list of value, where each element can itself contain whitespace. Compare the difference:

数组只是一个特殊的参数,它可以包含一个更结构化的值列表,其中每个元素本身可以包含空格。比较差异:

array=("item 1" "item 2" "item 3")
for i in "${array[@]}"; do   # The quotes are necessary here
    echo "$i"
done

list='"item 1" "item 2" "item 3"'
for i in $list; do
    echo $i
done
for i in "$list"; do
    echo $i
done
for i in ${array[@]}; do
    echo $i
done

回答by DonCallisto

For make a list, simply do that

要列出清单,只需这样做

colors=(red orange white "light gray")

Technically is an array, but - of course - it has all list features.
Even python list are implemented with array

从技术上讲是一个数组,但是 - 当然 - 它具有所有列表功能。
甚至python列表也是用数组实现的