I am sure this a duplicate, but my search for relevant info went without finding anything.
I was using mapfile to read a file in, but the appliances I need to run the script on do not have it loaded. So I went for an alternative.
This is not my script, but a test script to prove my point.
I have a file that has a bunch of stats, shorten below for sanity.
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
I am using the following code to read in the file into an array (I want to use this array multiple times in the script). But upon echoing out line by line. I get command not found on each line. I cannot figure out how to resolve this.
#!/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
results in the following
/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've tried double qouting $i, single qouting $i, and qouting / unqouting the array. Nothing I've tried has resulted in anything but :command not found
This works:
getArray() {
array=() # Create array
while IFS= read -r line # Read a line
do
array+=("$line") # Append line to the array
done < "$1"
}
infile="/tmp/file"
getArray "$infile" # you would need a return value for "file=getArray $infile"
# and you would write it differently
for i in "${array[@]}";
do
echo "$i"
done
You had three issues:
file=getArray $infile
does not return the array read. You would need to change the function and the assignment for that to work:
in your loop.