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 字符串数组操作
#!/bin/bash
str_array=(
"string1"
"string2"
"string3"
"string4"
"string5"
)
for val in ${str_array[@]}
do
echo $val
done
echo "--------------------"
for ((i=0;i<${#str_array};i++))
do
echo ${str_array[i]}
done
#!/bin/bash
# 将 ls 文件存为数组,并对最后一个文件按数字大小排序
let j=0
files=$(ls report*)
for file in $files
do
arr[j]=$file
(( j++ ))
done
echo ${arr[j-1]}
# 只排序最后一个文件如下, 可用$arr访问其它文件,它是数组。
# $files 却不是数组,真是shit.
sort -n $file > 1.txt
mv 1.txt $file
echo "$file sort done!"