What is a simple way to run simple Linux Loop? How to read file line by line?
There are many-many way to read file in bash script, look at the first section where I used while loop along with pipe (|) (cat $FILE | while read line; do … ) and also incremented the value of (i) inside the loop and at the end I am getting the wrong value of i, the main reason is that the usage of pipe (|) will create a new sub-shell to read the file and any operation you do within this while loop (example – i++) will get lost when this sub-shell finishes the operation.
Commands:
while read data; do echo $data done <Crunchify_ListFile.txt
Another Sample Example:
#!/bin/bash # set count to 1 count=10 # continue until $count equals 15 while [ $count -le 15 ] do echo "Welcome $count times." count=$(( count+1 )) # increments $count done
Output:
bash-3.2$ ./Crunchify_Loop.sh Welcome to Crunchify Tutorial: 10 Welcome to Crunchify Tutorial: 11 Welcome to Crunchify Tutorial: 12 Welcome to Crunchify Tutorial: 13 Welcome to Crunchify Tutorial: 14 Welcome to Crunchify Tutorial: 15