Shell脚本将数组的值分配给变量

时间:2018-07-24 07:21:19

标签: linux bash shell

我想将文件数组中的值分配给变量$ filename0,$ filename1 ... etc

如何设置自动增加文件名并分配正确的值 结果应该是这样的 $ filename0 =文件数组[0] $ filename1 = filearray [1]

现在,这是我的代码

filearray=('tmp1.txt' 'tmp2.txt' 'tmp3.txt' 'tmp4.txt' 'tmp5.txt')
let i=0
while (( i <= 4 ));
do
        filename=${filearray[i]}
        i=$(( i+1 ))
done

对不起,最新更新:
现在,当文件名中有扩展名时,将提示
“语法错误:无效的算术运算符(错误标记为“ .txt”)“
但是在我回显$(filename1)

时可以
count=0
for i in ${filearray[@]};
do
        count=$(( count +1 ))
        declare filename$count=$i
done
y=0
while [ $y < $count ]
do
        y=$(( y + 1 ))
        echo $((filename$y))
done

1 个答案:

答案 0 :(得分:1)

似乎您想动态创建变量名。尽管这是可能的*,但几乎总是有一种更好的方法,例如,使用关联数组:

filearray=('tmp1.txt' 'tmp2.txt' 'tmp3.txt' 'tmp4.txt' 'tmp5.txt')

declare -A fileassoc

for ((i=0; i < ${#filearray[@]}; i++))
do
    fileassoc["filename$i"]=${filearray[i]}
done

# To illustrate:
for key in "${!fileassoc[@]}"
do
    echo "$key: ${fileassoc[$key]}"
done

# or
for ((i=0; i < ${#filearray[@]}; i++))
do
    key="filename$i"
    echo "$key: ${fileassoc[$key]}"
done

礼物:

filename4: tmp5.txt
filename1: tmp2.txt
filename0: tmp1.txt
filename3: tmp4.txt
filename2: tmp3.txt

(关联数组不是有序的,不一定必须是)

*使用名为eval的危险命令-即使有魔环,也有龙,不要去那里

相关问题