Read Files in Linux with While Loop

The method of using a while loop to read a file in Linux is as follows:

#!/bin/bash

# 定义要读取的文件名
file="file.txt"

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

The code above first specifies the file name to be read as file.txt, then uses a while loop structure to read the file line by line and print it to the terminal. Within the loop, the command IFS= read -r line is used to read each line of the file and save it in the variable “line,” then it is printed to the terminal using echo “$line” command.

By running the script above, you can read the content of the file file.txt line by line and output it to the terminal.

bannerAds