In Bash, you can read lines from files using various methods. Here are a few examples:
- Using
while
loop andread
command:
#!/bin/bash
# Read lines from a file using a while loop
while IFS= read -r line; do
echo "Line: $line"
done < "file.txt"
In this example, the while
loop reads each line from the file “file.txt” using the read
command. The -r
option prevents backslashes from being interpreted as escape characters, and IFS=
ensures that leading and trailing whitespace is preserved. The loop body can be customized to perform actions on each line.
- Using a
for
loop and input redirection:
#!/bin/bash
# Read lines from a file using a for loop
for line in $(< "file.txt"); do
echo "Line: $line"
done
In this example, the for
loop iterates over each word in the file “file.txt” using command substitution $(< "file.txt")
. The loop treats each line as a separate word, which may not be desirable if lines contain spaces. However, it can be useful in certain scenarios.
- Using
mapfile
command (requires Bash version 4 or later):
#!/bin/bash
# Read lines from a file using mapfile
mapfile -t lines < "file.txt"
# Process each line
for line in "${lines[@]}"; do
echo "Line: $line"
done
In this example, the mapfile
command reads the lines of the file “file.txt” into an array named lines
. The -t
option removes trailing newline characters. Subsequently, a for
loop iterates over each line in the array and performs the desired actions.
These examples demonstrate different approaches for reading lines from a file in Bash. Choose the method that suits your specific requirements and adapt it as needed for your script.