Bash For Loop: Read File Line by Line

In Linux, you can use a for loop to read the contents of a file line by line. Here is an example of using a for loop to read a file.

#!/bin/bash

# 指定要读取的文件
file="example.txt"

# 使用for循环逐行读取文件内容
for line in $(cat $file); do
    echo $line
done

In the above example, we start by specifying the file name to read as example.txt. Next, we use a for loop and the cat command to read the content of the file, storing each line in the variable “line.” Lastly, we use the echo command to output the content of each line.

Alternatively, if you only need to read the file contents line by line without performing any other operations, you can use a while loop and the read command to achieve this.

#!/bin/bash

# 指定要读取的文件
file="example.txt"

# 使用while循环逐行读取文件内容
while read -r line; do
    echo $line
done < $file

In this example, we utilize the read command to read each line of the file and store the results in the variable ‘line’. Then, we use the echo command to output the contents of each line. Note that the ‘<' symbol is used to redirect the file contents into the read command.

bannerAds