两种写法:
#!/bin/bash
# 写法1
cat test.txt | while read line
do
echo "1:${line}"
done
# 写法2
while read line
do
echo "2:${line}"
done < test.txt
运行截图:

本文展示 Bash Shell 中按行读取文件的两种写法:一是通过管道将 cat 输出传递给 while read 循环;二是使用输入重定向直接在循环中读取文件。两种方法均给出示例代码,适合运维人员快速参考。
两种写法:
#!/bin/bash
# 写法1
cat test.txt | while read line
do
echo "1:${line}"
done
# 写法2
while read line
do
echo "2:${line}"
done < test.txt
运行截图:

输入关键词搜索本站全部文章