Input: $
cat
sample.txt
This is sample
file
This 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 loop
echo
"###############################"
cat
$FILE |
while
read
line;
do
echo
"Line # $i: $line"
((i++))
done
echo
"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=1
while
read
line;
do
echo
"Line # $k: $line"
((k++))
done
< $FILE
echo
"Total number of lines in file: $k"
Output: $ .
/readfile
.sh
###############################
Line
# 1: This is sample file
Line
# 2: This is normal text file
Total number of lines
in
file
: 1
###############################
This
is
sample
file
This
is
normal
text
file
################################
Line
# 1: This is sample file
Line
# 2: This is normal text file
Total number of lines
in
file
: 3