【问题标题】:Error with saving text line into array将文本行保存到数组中时出错
【发布时间】:2012-09-19 15:23:48
【问题描述】:

我正在尝试从 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 

和文本文件 位置.txt

   /apps/IBM
   /usr/home
   /var/login

谁能告诉我我做错了什么? 我可能犯了一个我不知道的愚蠢错误……(我是 UNIX 的新手)

提前致谢

【问题讨论】:

  • 您真的想在这里使用bash 还是在AIX 上使用/bin/sh
  • 你的错误来自echo $(Unix_Array[$i])而不是echo ${Unix_Array[$i]}

标签: linux bash shell aix


【解决方案1】:

如果您使用的是 bash 4 或更高版本,则可以放弃 while read 循环以支持 readarray 命令:

readarray Unix_Array < location.txt

for line in "${Unix_Array[@]}"; do
    echo "$line"
done

【讨论】:

    【解决方案2】:

    只需删除${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
    

    【讨论】:

    • 并在您使用时更新至#!/bin/bash。在很多发行版中,默认 sh 不支持数组。
    猜你喜欢
    • 2020-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2014-08-09
    • 1970-01-01
    相关资源
    最近更新 更多