Read files using arrays in Bash script
I have following file with some numeric contents in it
bash-4.2$ cat /tmp/araytest.txt 1 2 3 4 5 6 7 8 9 10 11 12 13 14
If we would like save the file contents in Array. We can using following method.
while read LINE do ARRAY+=("$LINE") done < <(cat /tmp/araytest.txt)
Now we can use another Loop to read it line by line for further manipulation as show below.
for i in "${ARRAY[@]}"; do echo $i done
Therefore full shell script should look like show below
#!/bin/bash while read LINE do ARRAY+=("$LINE") done < <(cat /tmp/araytest.txt) for i in "${ARRAY[@]}"; do echo $i done
Save it into file i-e testArray.sh and execute it as show below
bash-4.2$ ./testArray.sh 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Thanks for visiting , dont forget to leave your feedback.
Regards
Raja Naveed
Hi! This post couldn’t be written any better! Reading through this post reminds me of my old room mate! He always kept chatting about this. I will forward this post to him. Fairly certain he will have a good read. Many thanks for sharing!