【发布时间】:2017-08-10 18:20:37
【问题描述】:
我确定这是重复的,但我搜索相关信息没有找到任何东西。
我正在使用 mapfile 读取文件,但我需要运行脚本的设备没有加载它。所以我选择了一个替代方案。
这不是我的脚本,而是一个测试脚本来证明我的观点。
我有一个包含大量统计信息的文件,为了理智,请在下面缩短。
Status
Availability : available
State : enabled
Reason : The virtual server is available
CMP : enabled
CMP Mode : all-cpus
Traffic ClientSide Ephemeral General
Bits In 0 0 -
Bits Out 0 0 -
Packets In 0 0 -
Packets Out 0 0 -
Current Connections 0 0 -
Maximum Connections 0 0 -
Total Connections 0 0 -
Min Conn Duration/msec - - 0
Max Conn Duration/msec - - 0
Mean Conn Duration/msec - - 0
Total Requests - - 0
我正在使用以下代码将文件读入一个数组(我想在脚本中多次使用这个数组)。但是在逐行呼应时。我在每一行都找不到命令。我不知道如何解决这个问题。
#!/bin/bash
getArray() {
array=() # Create array
while IFS= read -r line # Read a line
do
array+=("$line") # Append line to the array
done < "$1"
}
infile="/home/tony/Desktop/test.txt"
file=getArray $infile
for i in ${file[@]};
do :
echo "$i"
done
结果如下
/home/tony/Desktop/test.txt: line 1: Status: command not found
/home/tony/Desktop/test.txt: line 2: Availability: command not found
/home/tony/Desktop/test.txt: line 3: State: command not found
/home/tony/Desktop/test.txt: line 4: Reason: command not found
/home/tony/Desktop/test.txt: line 5: CMP: command not found
/home/tony/Desktop/test.txt: line 6: CMP: command not found
/home/tony/Desktop/test.txt: line 9: Traffic: command not found
/home/tony/Desktop/test.txt: line 10: Bits: command not found
我已经尝试过双引号 $i、单引号 $i 和 qouting / unqouting 数组。除了 :command not found 之外,我没有尝试过任何结果
【问题讨论】:
-
您可能会意外分词,Bash 将其解释为命令。试试
for i in "${file[@]}";do后面还有个流浪: -
刚刚更新了我的代码并对数组进行了双引号。结果还是一样:(
-
for i in "${file[@]}"; do : echo "$i" done导致找不到命令 -
你还有一个额外的
:还有,file=getArray $infile不工作,因为没有回报。