我正在尝试从location.txt中提取目录位置并将其保存到数组中,但它看起来不太好。当我执行脚本时,
我收到此错误
./test.sh: line 7: location.txt: No such file or directory bina@ajax $ ./test.sh
./test.sh: line 5: =/apps/IBM: No such file or directory
./test.sh: line 5: =/usr/home: No such file or directory
./test.sh: line 11: Unix_Array[0]: command not found
./test.sh: line 11: Unix_Array[1]: command not found
这是我的代码
#!/bin/sh
counter=0
while read -r line; do
${Unix_Array[${counter}]}=$line;
let counter=counter+1;
done < location.txt
for ((i=0 ;counter > i; i++))
do
echo $(Unix_Array[$i])
done
和文本文件 location.txt
/apps/IBM
/usr/home
/var/login
有人可以告诉我我做错了什么吗? 我可能犯了一个我不知道的愚蠢错误......(我在UNIX中真的很新)
提前致谢
答案 0 :(得分:1)
只需删除${}
上的第一个${Unix_Array[${counter}]}=$line;
,因为您只想分配给数组,而不是指定和检索其值,您的固定脚本将如下所示:
#!/bin/sh
counter=0
while read -r line; do
Unix_Array[${counter}]=$line;
let counter=counter+1;
done < location.txt
for ((i=0 ;counter > i; i++))
do
echo ${Unix_Array[$i]}
done
答案 1 :(得分:1)
如果您使用的是bash 4或更高版本,则可以放弃while read
循环以支持readarray
命令:
readarray Unix_Array < location.txt
for line in "${Unix_Array[@]}"; do
echo "$line"
done