How to read file using bash for loop ?
Here we will check a quick tip how to read a file using bash for loop.
We know this is easily possible with “do while” loop and other ways.
Lets have a look at this:
[root@nglinux ~]# ls > file [root@nglinux ~]# for i in $( < file); do echo "***"$i"---"; done ***anaconda-ks.cfg--- ***Desktop--- ***Documents--- ***Downloads--- ***edit_host.sh--- ***file--- ***install.log.syslog--- ***Music--- ***Pictures--- ***Public--- ***Templates--- ***test--- ***Videos--- [root@nglinux ~]#
We can also replace the character < with cat command.
[root@nglinux ~]# for i in $(cat file); do echo "***"$i"---"; done ***anaconda-ks.cfg--- ***Desktop--- ***Documents--- ***Downloads--- ***edit_host.sh--- ***file--- ***install.log.syslog--- ***Music--- ***Pictures--- ***Public--- ***Templates--- ***test--- ***Videos--- [root@nglinux ~]#
We use the above trick multiple times to perform some tasks easily in bash.
I hope you liked the trick.
Please do post your comments.