2009-12-10 26 views
56

如何在unix shell腳本中創建數組?unix shell中的數組?

+0

第一個是一個很大的問題,但到底是什麼程序執行的事情有什麼關係呢? – Frank 2009-12-10 06:28:07

+1

http://www.gnu.org/software/bash/manual/html_node/Arrays.html – 2014-01-19 07:36:06

+0

請參見:[Unix Bourne Shell中的數組](http://unix.stackexchange.com/questions/137566/arrays-in -unix-bourne-shell#137571) – agc 2016-08-24 20:06:18

回答

3

你可以試試以下類型:

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

打破目錄名稱與空格。使用一段時間閱讀變化IFS的循環來照顧這一點。 – ghostdog74 2009-12-10 06:22:49

9
#!/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腳本編程指南」

44
在bash

,創建數組這樣

arr=(one two three) 

調用元素

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

,要求用戶輸入,您可以使用閱讀

read -p "Enter your choice: " choice 

是你要求什麼?

5

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" 
+0

csh確實有數組。 – 2013-08-05 06:30:19

+0

@KeithThompson:沒有記錄在[手冊頁](http://linux.die.net/man/1/csh)中,但功能看起來至少在某些版本中存在。 – 2013-08-05 11:03:36

+2

手冊頁沒有提及該名稱的「數組」,但查看'set'命令的文檔('set name =(wordlist)'')和「Variable substituion」部分('$ name [selector]'和'$ {name [selector]}')。據我所知,csh一直支持數組。例如,參見'$ path'數組變量,它反映了'$ PATH'環境變量。 – 2013-09-19 15:45:20

0

在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)) ]} 
+0

顯示最後一個元素的更簡潔的方法是'echo「$ {array [@]:( - 1)}」'。這消除了兩次寫入數組變量名的需要。 – 2014-02-26 22:20:05

5

試試這個:

echo "Find the Largest Number and Smallest Number of a given number" 
echo "---------------------------------------------------------------------------------" 
echo "Enter the number" 
read n 

while [ $n -gt 0 ] #For Seperating digits and Stored into array "x" 
do 
     x[$i]=`expr $n % 10` 
     n=`expr $n/10` 
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" 
12

Bourne 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 
+1

Bash支持數組。不知道關於原始的Bourne shell,但是bash現在更流行... – plesiv 2013-08-05 06:16:39

+2

@zplesivcak - ...在GNU/Linux上,因爲它是一個GNU的東西。例如,* FreeBSD *不附帶'bash'(它可以從端口安裝)。用'bash'功能編寫的腳本不是可移植的,它們比大多數Bourne shell實現(例如'dash',它在* GNU/Linux發行版上很常見)慢得多。 'bash'是一個很好的交互式shell,但是腳本運行速度很慢。 – tjameson 2013-10-31 18:36:12

+1

'$ *'被認爲是有害的。通常情況下,'$ @'是首選,因爲它是一樣的,但是保留空格。 '$ @'擴展爲「$ 1」「$ 2」「$ 3」...「$ n」,而$ *'擴展爲「$ 1x $ 2x $ 3x ... $ n」,其中'x'是'$ IFS'分隔符(很可能是空格)。 – zserge 2014-02-14 18:15:07

1

要讀取從keybord的值和插入元件成陣列

# 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 
56

以下代碼在shell中創建並打印一組字符串:

#!/bin/bash 
array=("A" "B" "ElementC" "ElementE") 
for element in ${array[@]} 
do 
    echo $element 
done 

echo "" 
echo "Nbr of elements:" ${#array[@]} 

echo "" 
echo ${array[@]} 

結果:

A 
B 
ElementC 
ElementE 

Nbr of elements: 4 

A B ElementC ElementE 
+9

你確定它適用於'#!/ bin/sh' shebang嗎?我想你需要使用'#!/ bin/bash'來使用它。 – timurb 2013-12-14 16:40:26

+0

謝謝Erthad。的確,我將它改爲#!/ bin/bash。 – 2015-01-27 14:33:47

3

如果你想用空間支持鍵值存儲使用-A參數:使用declare -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「關聯數組。 「

4

一個數組可以在兩個方向加載。

set -A TEST_ARRAY alpha beta gamma 

X=0 # Initialize counter to zero. 

- 加載與琴絃的α,β,γ

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

而且數組,我想下面的信息可以幫助:

該shell支持一維數組。陣列 元素的最大數量是1,024。當定義一個數組時,它會自動標註爲1,024個元素,尺寸爲 。一維數組包含數組元素的序列,這就像在火車軌道上連接 的boxcars一樣。

如果您要訪問的數組:

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 
3

你的問題詢問有關 「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]}" 
second element 

你可以得到所有元素通過"${myArray[@]}"。您可以使用切片符號$ {array [@]:start:length}來限制引用的數組部分,例如"${myArray[@]:1}"要留下第一個元素。

該數組的長度爲${#myArray[@]}。您可以使用"${!myArray[@]}"獲取包含現有數組中所有索引的新數組。

在ksh93之前的ksh的早期版本也有數組,但不是基於括號的表示法,也不支持切片。你可以創建一個數組,這樣,雖然:

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