read a file line by line
Go through a file's lines in a script, also split into fields, without losing spaces or backslashes.
shelltextdevelopment
steps
-
while IFS= read -r line; do echo "$line"; done < file.txteach line as it is
-
while IFS=, read -r name age; do echo "$name is $age"; done < people.csveach line split at the commas
-
command | while IFS= read -r line; do echo "$line"; doneeach line of a command's output
-
mapfile -t lines < file.txtevery line into an array at once (bash 4)
notes
for line in $(cat file)splits at every space, not at lines: use while read.- A last line without a newline is skipped by read:
|| [ -n "$line" ]keeps it.
commands used
readmapfile
Each has a page in lore: lore read opens it.
ask for input in a script
Ask yes or no, read a password without showing it, or wait for an answer with a time limit.
check if a file or folder exists
Test in a script whether a path exists, is a file, a folder, empty or runnable.
check if a string contains a text
Test in a script whether a string contains, starts with or matches something.
count lines of code
How many lines of code a project has, in total and by language.