2

Shell中逐行读取重定向输入

 2 years ago
source link: http://blog.colorccm.com/2020/11/02/it/shell_whileread/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Shell中逐行读取重定向输入

发表于2020-11-02|更新于2020-11-02|it

在Linux中使用shell处理多行的重定向输入,可以使用以下几种处理方法:

使用for的方式

shell
for i in $(ls)
do
echo $i
done
#或者
for i in `ls`
do
echo $i
done

需要注意的是,这种方法不是以换行符作为分隔的,是以空格进行分隔

shell
for i in $(ls -lrt)
do
echo $i
done
#这样显示出来不是每一行,而是每一个空格分隔的数据,包括文件属性、大小等

使用while … read的方式

以下两种方法都是以换行符作为分割的
方式一

shell
cat test.txt | while read i
do
echo $i
done
#或者
ls -lrt | while read i
do
done

注意:这种方法如果需要对外部变量进行操作,操作结果是无法更新到外部参数的,跳出循环后外部参数还是原值,不会发生变化。
如果要实现对外部参数进行操作且生效的,可以使用方法二。

方式二

shell
while read i
do
echo $i
done <test.txt

注意:这种方法可以操作外部变量,但是重定向必须是一个文件,而不可以使用``


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK