Original article address:
There are many methods to read files using bash scripts. Please refer to the first part. I used the while loop and the pipeline command (|) (cat $ file | while read line; do... ), And increment the I value in the loop. Finally, I get the I that is not what I think. The main reason is that the pipeline command will initiate a sub-shell to read the file, and any operations in the (sub-shell) while loop (such as I ++ ), will be lost with the completion of the sub-shell.
The second is the worst. The most obvious error is that the For Loop (for fileline in $ (cat $ file) is used during file reading ); do ..), in this way, the row is changed every time a word is printed, because the for loop uses spaces as the default ifs.
The perfect method is the third while loop (While read line; do .... Done <$ File) Is the most suitable and simple method for reading files in one row. See the following example.
Input: $ cat sample.txt This is sample fileThis is normal text file Source: $ cat readfile.sh #!/bin/bash i=1;FILE=sample.txt # Wrong way to read the file.# This may cause problem, check the value of ‘i‘ at the end of the loopecho "###############################"cat $FILE | while read line; do echo "Line # $i: $line" ((i++))doneecho "Total number of lines in file: $i" # The worst way to read file.echo "###############################"for fileline in $(cat $FILE);do echo $fileline done # This is correct way to read file.echo "################################"k=1while read line;do echo "Line # $k: $line" ((k++))done < $FILEecho "Total number of lines in file: $k" Output: $ ./readfile.sh ###############################Line # 1: This is sample fileLine # 2: This is normal text fileTotal number of lines in file: 1###############################ThisissamplefileThisisnormaltextfile################################Line # 1: This is sample fileLine # 2: This is normal text fileTotal number of lines in file: 3