Linux Shell 脚本数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8545943/
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 03:42:07  来源:igfitidea点击:

Shell script arrays

linuxarraysbashloops

提问by Gábor Varga

I would like to set array elements with loop:

我想用循环设置数组元素:

for i in 0 1 2 3 4 5 6 7 8 9
do
array[$i] = 'sg'
done

echo $array[0]
echo $array[1]

So it does not work. How to..?

所以它不起作用。如何..?

回答by Oliver Charlesworth

Remove the spaces:

删除空格:

array[$i]='sg'

Also, you should access the elements as*:

此外,您应该以* 的形式访问元素:

echo ${array[0]}

See e.g. http://tldp.org/LDP/abs/html/arrays.html.

参见例如http://tldp.org/LDP/abs/html/arrays.html



* Thanks to @Mat for reminding me of this!* 感谢@Mat 提醒我这一点!

回答by harish.venkat

there is problem with your echo statement: give ${array[0]}and ${array[1]}

你的 echo 语句有问题:给${array[0]}${array[1]}

回答by Zsolt Botykai

It should work if you had declared your variable as array, and print it properly:

如果您已将变量声明为数组,并正确打印它,它应该可以工作:

declare -a array
for i in 0 1 2 3 4 5 6 7 8 9 
do
    array[$i]="sg"
done
echo ${array[0]} 
echo ${array[1]} 

See it in action here.

这里查看它的实际效果。

HTH

HTH

回答by sehe

My take on that loop:

我对那个循环的看法:

array=( $(yes sg | head -n10) )

Or even simpler:

或者更简单:

array=( sg sg sg sg sg sg sg sg sg sg )

See http://ideone.com/DsQOZfor some proof. Note also, bash 4+ readarray:

请参阅http://ideone.com/DsQOZ以获取一些证据。另请注意,bash 4+ readarray:

readarray array -t -n 10 < <(yes "whole lines in array" | head -n 10)

In fact, readarray is most versatile, e.g. get the top 10 PIDs of processes with bash in the name into array (which could return an array size<10 if there aren't 10 such processes):

事实上, readarray 是最通用的,例如将名称中带有 bash 的进程的前 10 个 PID 放入数组(如果没有 10 个这样的进程,它可以返回一个数组大小<10):

readarray array -t -n 10 < <(pgrep -f bash)

回答by Praveen Kumar Verma

# Declare Array

NAMEOFSEARCHENGINE=( Google Yahoo Bing Blekko Rediff )

# get length of an array
arrayLength=${#NAMEOFSEARCHENGINE[@]}

# use for loop read all name of search engine
for (( i=0; i<${arrayLength}; i++ ));
do
  echo ${NAMEOFSEARCHENGINE[$i]}
done

Output:

输出:

Google
Yahoo
Bing
Blekko
Rediff

Google
Yahoo
Bing
Blekko
Rediff