unix shell中的数组?

Aru*_*lam 78 unix arrays bash shell

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

小智 87

以下代码在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[@]}"
Run Code Online (Sandbox Code Playgroud)

结果:

A
B
ElementC
ElementE

Number of elements: 4

A B ElementC ElementE
Run Code Online (Sandbox Code Playgroud)


gho*_*g74 60

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

arr=(one two three)
Run Code Online (Sandbox Code Playgroud)

调用元素

$ echo "${arr[0]}"
one
$ echo "${arr[2]}"
three
Run Code Online (Sandbox Code Playgroud)

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

read -p "Enter your choice: " choice
Run Code Online (Sandbox Code Playgroud)

  • 空格分隔的声明不适用于`/bin/sh`,抛出错误`第1行:语法错误:意外的“(”`。您知道替代方案吗? (4认同)

小智 18

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

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

$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two
Run Code Online (Sandbox Code Playgroud)

使用变量评估:

$ 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
Run Code Online (Sandbox Code Playgroud)

  • Bash 支持数组。不确定原始的 Bourne shell,但 bash 如今更流行...... (3认同)
  • @zplesivcak - 在GNU/Linux上,因为它是一个GNU的东西.例如,*FreeBSD*不附带`bash`(虽然它可以从端口安装).假设`bash`特性编写的脚本不可移植,并且它们比大多数Bourne shell实现慢得多(比如`dash`,*在GNU/Linux发行版上很常见).`bash`是一个很好的交互式shell,但脚本编写很慢. (2认同)

Lai*_*han 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
Run Code Online (Sandbox Code Playgroud)

你可以阅读ABS"Advanced Bash-Scripting Guide"

  • 请重新考虑建议将ABS作为学习资源-它以多种方式抨击W3Schools对HTML和Javascript的含义,拥有大量的Google汁液,但在许多示例中都展示了不良做法,并且很少且不充分地进行了更新。[bash-hackers的Wiki](http://wiki.bash-hackers.org/syntax/arrays)是更好的资源。[BashGuide](https://mywiki.wooledge.org/BashGuide/Arrays)也是如此。 (2认同)

Pau*_*ce. 8

Bourne shell和C shell没有阵列,IIRC.

除了其他人所说的,在Bash中你可以得到数组中的元素数量,如下所示:

elements=${#arrayname[@]}
Run Code Online (Sandbox Code Playgroud)

并进行切片式操作:

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"
Run Code Online (Sandbox Code Playgroud)

  • 手册页没有提到该名称的"数组",但请参阅`set`命令(`set name =(wordlist)`)和"Variable substituion"部分(`$ name [selector]`和`$ {名称[选择器]}`).据我所知,csh一直支持数组.例如,参见`$ path`数组变量,它反映了`$ PATH`环境变量. (2认同)

小智 7

试试这个 :

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"
Run Code Online (Sandbox Code Playgroud)


Mar*_*eed 6

您的问题询问"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)
Run Code Online (Sandbox Code Playgroud)

和访问这样的元素

$ echo "${myArray[1]}"
second element
Run Code Online (Sandbox Code Playgroud)

你可以通过获得所有元素"${myArray[@]}".您可以使用切片表示法$ {array [@]:start:length}来限制引用的数组部分,例如"${myArray[@]:1}",不要使用第一个元素.

数组的长度是${#myArray[@]}.您可以获取一个包含现有数组中所有索引的新数组"${!myArray[@]}".

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

set -A myArray -- first "second element" 3rd 
Run Code Online (Sandbox Code Playgroud)


Roo*_*eti 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
Run Code Online (Sandbox Code Playgroud)


Pin*_*jee 5

数组可以双向加载。

set -A TEST_ARRAY alpha beta gamma
Run Code Online (Sandbox Code Playgroud)

要么

X=0 # Initialize counter to zero.
Run Code Online (Sandbox Code Playgroud)

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

for ELEMENT in alpha gamma beta
do
    TEST_ARRAY[$X]=$ELEMENT
    ((X = X + 1))
done
Run Code Online (Sandbox Code Playgroud)

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

外壳支持一维数组。数组元素的最大数量为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
Run Code Online (Sandbox Code Playgroud)