linux shell 陣列的長度計算、修改、迴圈輸出等操作
阿新 • • 發佈:2019-02-14
在shell中,陣列變數的複製有兩種方法:
(1) name = (value1 ... valuen)此時下標從0開始
(2) name[index] = value
example:
#1/bin/sh #arrayTest name=(yunix yhx yfj) echo "array is:${name[@]}" echo "array length is:${#name[*]}" echo ${name[1]} name[1]=yang echo ${name[1]} read -a name echo ${name[1]} echo "loop the array" len=${#name[*]} i=0 while [ $i -lt $len ] do echo ${name[$i]} let i++ done
result:
array is:yunix yhx yfj
array length is:3
yhx
yang
a b c d e
b
loop the array
a
b
c
d
e
下面的是關於陣列的輸出例項
example:
#!/bin/sh #arrayLoopOut read -a array len=${#array[*]} echo "array's length is $len" echo "use while out the array:" i=0 while [ $i -lt $len ] do echo -n "${array[$i]}" let i++ done echo echo "use for out the array:" for ((j=0;j<"$len";j=j+1)) do echo -n ${array[$j]} done echo echo "use for in out the array:" for value in ${array[*]} do echo -n $value done
result:
a b c d e f g
array's length is 7
use while out the array:
abcdefg
use for out the array:
abcdefg
use for in out the array:
abcdefg