Snippets

Marc Richter Bash - for line in file

Created by Marc Richter
#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do
    echo "Text read from file: $line"
done < "$1"


Explanation:

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).

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.