To loop through the contents of a file in Bash, you can use a for
loop and the read
command.
Here's an example of how you can use a for
loop to read and process each line in a file:
#!/bin/bash # Set the input file input_file=input.txt # Open the input file while IFS= read -r line; do # Process the line echo "Line: $line" done < "$input_file"
This script will open the file input.txt
and read each line in the file one by one. The while
loop reads each line and stores it in the line
variable, which you can then process in the body of the loop.
You can also use a while
loop and the read
command to process the output of a command:
#!/bin/bash # Set the command to run command="ls -l" # Run the command and process the output while IFS= read -r line; do # Process the line echo "Line: $line" done < <(eval "$command")
This script will run the ls -l
command and read the output line by line. The <(eval "$command")
syntax is known as process substitution, which allows you to use the output of a command as the input to a while
loop.
Keep in mind that the read
command will stop reading when it encounters the end of the file or the end of the command output. To read the entire file or command output, you need to use a loop like this.