bash 数组操作

bash 仅支持一维数组。 而且数组下标是从0开始的
为数组赋值:
array=(1 4 7 2 5 8)     #以空格为分割符,()为数组
str="this is test string"
str_arr=($str);         #默认以空格分割
数组遍历:
for val in ${str_arr[@]};do echo $val; done
for file in `ls`;do echo $file; done
数组元素个数: ${#array[@]}

举例: 将一个字符串的每个字符分割为数组。

cat 1.sh

#!/bin/bash
str="long string"
for((i=0;i<${#str};i++))
do a[i]=${str:$i:1}
    echo ${a[i]}
done;
echo $a                    # $a 只会输出一个l
echo ${a[*]}              #${a[*]} 和 ${a[@] 会输出数组
echo ${a[@]}            #这两者差别使用时再详细辨析,

./1.sh
l
o
n
g

s
t
r
i
n
g
l
l o n g s t r i n g
l o n g s t r i n g


你可能感兴趣的:(bash,编程)