bash unix shell 中的数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1878882/
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
Arrays in unix shell?
提问by Arunachalam
How do I create an array in unix shell scripting?
如何在 unix shell 脚本中创建数组?
回答by Vincent Agami
The following code creates and prints an array of strings in shell:
以下代码在 shell 中创建并打印一个字符串数组:
#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
echo "$element"
done
echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"
Result:
结果:
A
B
ElementC
ElementE
Number of elements: 4
A B ElementC ElementE
回答by ghostdog74
in bash, you create array like this
在 bash 中,您可以像这样创建数组
arr=(one two three)
to call the elements
调用元素
$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three
to ask for user input, you can use read
要要求用户输入,您可以使用 read
read -p "Enter your choice: " choice
回答by Mishka
Bourne shell doesn't support arrays. However, there are two ways to handle the issue.
Bourne shell 不支持数组。但是,有两种方法可以处理此问题。
Use positional shell parameters $1, $2, etc.:
使用位置 shell 参数 $1、$2 等:
$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo
two
Use variable evaluations:
使用变量评估:
$ n=1 ; eval a$n="one"
$ n=2 ; eval a$n="two"
$ n=3 ; eval a$n="three"
$ n=2
$ eval echo $a$n
two
回答by Lai Jiangshan
#!/bin/bash
# define a array, space to separate every item
foo=(foo1 foo2)
# access
echo "${foo[1]}"
# add or changes
foo[0]=bar
foo[2]=cat
foo[1000]=also_OK
You can read the ABS "Advanced Bash-Scripting Guide"
您可以阅读 ABS“高级 Bash 脚本指南”
回答by muthukrishnavinayagam
Try this :
尝试这个 :
echo "Find the Largest Number and Smallest Number of a given number"
echo "---------------------------------------------------------------------------------"
echo "Enter the number"
read n
i=0
while [ $n -gt 0 ] #For Seperating digits and Stored into array "x"
do
x[$i]=`expr $n % 10`
n=`expr $n / 10`
i=`expr $i + 1`
done
echo "Array values ${x[@]}" # For displaying array elements
len=${#x[*]} # it returns the array length
for (( i=0; i<len; i++ )) # For Sorting array elements using Bubble sort
do
for (( j=i+1; j<len; j++ ))
do
if [ `echo "${x[$i]} > ${x[$j]}"|bc` ]
then
t=${x[$i]}
t=${x[$i]}
x[$i]=${x[$j]}
x[$j]=$t
fi
done
done
echo "Array values ${x[*]}" # Displaying of Sorted Array
for (( i=len-1; i>=0; i-- )) # Form largest number
do
a=`echo $a \* 10 + ${x[$i]}|bc`
done
echo "Largest Number is : $a"
l=$a #Largest number
s=0
while [ $a -gt 0 ] # Reversing of number, We get Smallest number
do
r=`expr $a % 10`
s=`echo "$s * 10 + $r"|bc`
a=`expr $a / 10`
done
echo "Smallest Number is : $s" #Smallest Number
echo "Difference between Largest number and Smallest number"
echo "=========================================="
Diff=`expr $l - $s`
echo "Result is : $Diff"
echo "If you try it, We can get it"
回答by Paused until further notice.
The Bourne shell and C shell don't have arrays, IIRC.
Bourne shell 和 C shell 没有数组,IIRC。
In addition to what others have said, in Bash you can get the number of elements in an array as follows:
除了其他人所说的,在 Bash 中,您可以按如下方式获取数组中的元素数:
elements=${#arrayname[@]}
and do slice-style operations:
并进行切片式操作:
arrayname=(apple banana cherry)
echo ${arrayname[@]:1} # yields "banana cherry"
echo ${arrayname[@]: -1} # yields "cherry"
echo ${arrayname[${#arrayname[@]}-1]} # yields "cherry"
echo ${arrayname[@]:0:2} # yields "apple banana"
echo ${arrayname[@]:1:1} # yields "banana"
回答by Mark Reed
Your question asks about "unix shell scripting", but is tagged bash
. Those are two different answers.
您的问题询问“unix shell 脚本”,但被标记为bash
. 这是两个不同的答案。
The POSIX specification for shells does not have anything to say about arrays, as the original Bourne shell did not support them. Even today, on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh
does not have array support. So if you want your script to work in different Bourne-compatible shells, you shouldn't use them. Alternatively, if you are assuming a specific shell, then be sure to put its full name in the shebang line, e.g. #!/usr/bin/env bash
.
shell 的 POSIX 规范对数组没有任何说明,因为原始的 Bourne shell 不支持它们。即使在今天,在 FreeBSD、Ubuntu Linux 和许多其他系统上,/bin/sh
也不支持阵列。因此,如果您希望脚本在不同的 Bourne 兼容 shell 中工作,则不应使用它们。或者,如果您假设有一个特定的 shell,那么一定要在 shebang 行中输入它的全名,例如#!/usr/bin/env bash
.
If you are using bashor zsh, or a modern version of ksh, you can create an array like this:
如果您使用的是bash或zsh,或现代版本的ksh,您可以创建一个这样的数组:
myArray=(first "second element" 3rd)
and access elements like this
并访问这样的元素
$ echo "${myArray[1]}"
second element
You can get all the elements via "${myArray[@]}"
. You can use the slice notation ${array[@]:start:length}to restrict the portion of the array referenced, e.g. "${myArray[@]:1}"
to leave off the first element.
您可以通过"${myArray[@]}"
. 您可以使用切片符号${array[@]:start:length}来限制引用的数组部分,例如"${myArray[@]:1}"
,去掉第一个元素。
The length of the array is ${#myArray[@]}
. You can get a new array containing all the indexes from an existing array with "${!myArray[@]}"
.
数组的长度是${#myArray[@]}
。您可以获得一个包含现有数组中所有索引的新数组"${!myArray[@]}"
。
Older versions of ksh before ksh93 also had arrays, but not the parenthesis-based notation, nor did they support slicing. You could create an array like this, though:
ksh93 之前的旧版 ksh 也有数组,但没有基于括号的表示法,也不支持切片。不过,您可以创建一个这样的数组:
set -A myArray -- first "second element" 3rd
回答by Pinaki Mukherjee
An array can be loaded in twoways.
可以通过两种方式加载数组。
set -A TEST_ARRAY alpha beta gamma
or
或者
X=0 # Initialize counter to zero.
-- Load the array with the strings alpha, beta, and gamma
-- 用字符串 alpha、beta 和 gamma 加载数组
for ELEMENT in alpha gamma beta
do
TEST_ARRAY[$X]=$ELEMENT
((X = X + 1))
done
Also, I think below information may help:
另外,我认为以下信息可能会有所帮助:
The shell supports one-dimensional arrays. The maximum number of array elements is 1,024. When an array is defined, it is automatically dimensioned to 1,024 elements. A one-dimensional array contains a sequence of array elements, which are like the boxcars connected together on a train track.
shell 支持一维数组。数组元素的最大数量为 1,024。定义数组后,它会自动调整为 1,024 个元素。一维数组包含一系列数组元素,它们就像火车轨道上连接在一起的棚车。
In case you want to access the array:
如果要访问数组:
echo ${MY_ARRAY[2] # Show the third array element
gamma
echo ${MY_ARRAY[*] # Show all array elements
- alpha beta gamma
echo ${MY_ARRAY[@] # Show all array elements
- alpha beta gamma
echo ${#MY_ARRAY[*]} # Show the total number of array elements
- 3
echo ${#MY_ARRAY[@]} # Show the total number of array elements
- 3
echo ${MY_ARRAY} # Show array element 0 (the first element)
- alpha
回答by Roopesh Majeti
You can try of the following type :
您可以尝试以下类型:
#!/bin/bash
declare -a arr
i=0
j=0
for dir in $(find /home/rmajeti/programs -type d)
do
arr[i]=$dir
i=$((i+1))
done
while [ $j -lt $i ]
do
echo ${arr[$j]}
j=$((j+1))
done
回答by Manjotsingh Chug
There are multiple ways to create an array in shell.
有多种方法可以在 shell 中创建数组。
ARR[0]="ABC"
ARR[1]="BCD"
echo ${ARR[*]}
${ARR[*]}
prints all elements in the array.
${ARR[*]}
打印数组中的所有元素。
Second way is:
第二种方式是:
ARR=("A" "B" "C" "D" 5 7 "J")
echo ${#ARR[@]}
echo ${ARR[0]}
${#ARR[@]}
is used to count length of the array.
${#ARR[@]}
用于计算数组的长度。