如何在 Unix shell 脚本中创建数组?

问题描述 投票:0回答:14

如何在 Unix shell 脚本中创建数组?

arrays bash shell unix
14个回答
103
投票

以下代码在 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[@]}"

结果:

A
B
ElementC
ElementE

Number of elements: 4

A B ElementC ElementE

63
投票

在 bash 中,你可以像这样创建数组

arr=(one two three)

调用元素

$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three

要请求用户输入,您可以使用 read

read -p "Enter your choice: " choice

27
投票

Bourne shell 不支持数组。但是,有两种方法可以解决这个问题。

使用位置 shell 参数 $1、$2 等:

$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two

使用变量评估:

$ 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

13
投票
#!/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

您可以阅读 ABS 《高级 Bash 脚本指南》


11
投票

您的问题询问“unix shell 脚本”,但被标记为

bash
。这是两个不同的答案。

shell 的 POSIX 规范没有任何关于数组的内容,因为原始的 Bourne shell 不支持它们。即使在今天,在 FreeBSD、Ubuntu Linux 和许多其他系统上,

/bin/sh
也不支持数组。因此,如果您希望脚本在不同的 Bourne 兼容 shell 中工作,则不应使用它们。或者,如果您假设使用特定的 shell,请务必将其全名放在 shebang 行中,例如
#!/usr/bin/env bash

如果您使用 bashzsh,或者现代版本的 ksh,您可以创建一个像这样的数组:

myArray=(first "second element" 3rd)

并像这样访问元素

$ echo "${myArray[1]}" # for bash/ksh; for zsh, echo $myArray[2]
second element

您可以通过

"${myArray[@]}"
获取所有元素。您可以使用切片符号 ${array[@]:start:length} 来限制引用的数组部分,例如
"${myArray[@]:1}"
省略第一个元素。

数组的长度为

${#myArray[@]}
,在zsh中可以简化为
$#myArray
。在 bash 和 ksh 中,您可以使用
"${!myArray[@]}"
获取一个包含现有数组中所有索引的新数组;在 zsh 中,您必须手动构造范围,但是
{1..$#myArray}
可以工作,因为它还在大括号扩展之前进行参数扩展。

ksh93 之前的旧版本 ksh 也有数组,但没有基于括号的表示法,也不支持切片。不过,您可以创建一个像这样的数组:

set -A myArray -- first "second element" 3rd 

8
投票

Bourne shell 和 C shell 没有数组,IIRC。

除了其他人所说的之外,在 Bash 中您还可以获取数组中的元素数量,如下所示:

elements=${#arrayname[@]}

并进行切片式操作:

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"

8
投票

试试这个:

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"

5
投票

您可以尝试以下类型:

#!/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

5
投票

数组可以通过两种方式加载。

set -A TEST_ARRAY alpha beta gamma

X=0 # Initialize counter to zero.

-- 使用字符串 alpha、beta 和 gamma 加载数组

for ELEMENT in alpha gamma beta
do
    TEST_ARRAY[$X]=$ELEMENT
    ((X = X + 1))
done

另外,我认为以下信息可能会有所帮助:

shell支持一维数组。数组最大数量 元素为 1,024。当数组被定义时,它会自动 尺寸为 1,024 个元素。一维数组包含一个 数组元素的序列,就像连接的棚车 一起在火车轨道上。

如果您想访问数组:

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

4
投票

如果您想要支持空格的键值存储,请使用

-A
参数:

declare -A programCollection
programCollection["xwininfo"]="to aquire information about the target window."

for program in ${!programCollection[@]}
do
    echo "The program ${program} is used ${programCollection[${program}]}"
done

http://linux.die.net/man/1/bash“关联数组是使用声明-A名称创建的。”


4
投票

在 shell 中创建数组的方法有多种。

ARR[0]="ABC"
ARR[1]="BCD"
echo ${ARR[*]}

${ARR[*]}
打印数组中的所有元素。

第二种方法是:

ARR=("A" "B" "C" "D" 5 7 "J")
echo ${#ARR[@]}
echo ${ARR[0]}

${#ARR[@]}
用于计算数组的长度。


3
投票

从键盘读取值并将元素插入数组

# enter 0 when exit the insert element
echo "Enter the numbers"
read n
while [ $n -ne 0 ]
do
    x[$i]=`expr $n`
    read n
    let i++
done

#display the all array elements
echo "Array values ${x[@]}"
echo "Array values ${x[*]}"

# To find the array length
length=${#x[*]}
echo $length

2
投票

一个简单的方法:

arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array

len=${#arr[*]}  #determine length of array

# iterate with for loop
for (( i=0; i<len; i++ ))
do
    echo ${arr[$i]}
done

1
投票

在 ksh 中你可以这样做:

set -A array element1 element2 elementn

# view the first element
echo ${array[0]}

# Amount elements (You have to substitute 1)
echo ${#array[*]}

# show last element
echo ${array[ $(( ${#array[*]} - 1 )) ]}
© www.soinside.com 2019 - 2024. All rights reserved.