Read lines from a file and perform actions for each of them in Bash
Create a new script file
nano test.sh
Paste the below code and change the loop according to your needs.
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
echo "Text read from file: $line"
done < "$1"
Make the script executable
chmod +x test.sh
Run the script with the path of your text file as a parameter
test.sh path/to/test/file.txt
Explaination
- IFS=” (or IFS=) prevents leading/trailing whitespace from being trimmed.
- -r prevents backslash escapes from being interpreted.
- || [[ -n $line ]] prevents the last line from being ignored if it doesn’t end with a \n (since read returns a non-zero exit code when it encounters EOF).
Source
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.