There are many ways to read a file in Linux. This blog post shows a few of them.
Sample file
For our examples, we will use this file animals.txt. We will read it line by line and print each animal name.
alligator bear cat dog elephant fox gorilla hippopotamus iguana jellyfish
Use read -r with IFS
Create a file readlinebyline.sh and add these lines to it:
#!/bin/bash
while IFS= read -r animal; do
echo "$animal"
done < /PATH/TO/animals.txt
Chmod the shell script to 755.
chmod +x readlinebyline.sh
Run the script:
./readlinebyline.sh
The IFS=
option is used to prevent leading or trailing whitespaces from being trimmed.
Use read -r
Create a file readlinebyline.sh and add these lines to it:
#!/bin/bash
while read -r animal; do
echo "$animal"
done < /PATH/TO/animals.txt
Chmod the shell script to 755.
chmod +x readlinebyline.sh
Run the script:
./readlinebyline.sh
What shells and environments does this work for?
This works for bash, tcsh, sh, zsh and ksh, as well as macOS.
Conclusion
If you have found this blog post useful, add a comment below. Thanks for reading.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.