HowTo: Bash For While Loop Through File Contents Script

Here is a basic script in bash for looping through the contents of a file using a while loop:

#!/bin/bash

# specify the file you want to read
filename="file.txt"

# open the file using a file descriptor
# the -r option is to read the file
exec 3<&0
exec 0<$filename

# while loop to read the file line by line
while read line
do
# process each line here
echo $line
done

# close the file descriptor
exec 0<&3

In this example, the exec command is used to open the file specified by the filename variable and assign it to file descriptor 0 (standard input). The while loop then reads each line of the file, one line at a time, and processes it in the loop body. The exec command at the end closes the file descriptor and restores the original standard input.

You can modify the loop body to perform any desired actions on each line of the file, such as processing or transforming the data.

Leave a Comment