【shell】脚本读取输入重定向(<)文件

shell脚本使用<来重定向输入,如,< filename.txt 将文件重定向到标准输入,如何在脚本中读取文件内容呢?

1. 使用read逐行读取

准备

同一目录下分别创建 test.sh text.txt两个文件

touch test.sh
touch text.txt

文件内容:

  • text.txt
hello world
1
2
3
4 5 6
  • test.sh
#!/bin/bash

while read line; do
  echo $line
done

添加执行权限:

chmod a+x test.sh

使用

./test.sh < text.txt

输出:

hello world
1
2
3
4 5 6

2. 使用for in

修改test.sh文件,需修改IFS变量以实现逐行读取

#!/bin/bash

TEMPIFS=$IFS
IFS=$(echo -en "\n") #等效于$(echo -e -n "\n") 
for lin in `cat <&0`; do # `cat <&0` 读取标签输入
  echo $lin
done
IFS=TEMPIFS

使用

./test.sh < text.txt

输出:

hello world
1
2
3
4 5 6

如果没有修改IFS变量,将按空格(或tab,或\n)分隔读取,不是按行:

#!/bin/bash

for lin in `cat <&0`; do
  echo $lin
done

输出:

hello
world
1
2
3
4
5
6
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,539评论 0 5
  • 第1章 小试牛刀 $ 是普通用户,# 表示管理员用户 root。 shebang:#!。sharp / hash ...
    巴喬書摘阅读 6,477评论 1 4
  • 建立一个脚本 Linux中有好多中不同的shell,但是通常我们使用bash (bourne again shel...
    某人在阅读 2,062评论 0 0
  • 第 2 章 SHELL 基础知识2.1 shell脚本我们在上面简单介绍了一下什么是shell脚本,现在我们来进一...
    LiWei_9e4b阅读 1,602评论 0 0
  • linux文件描述符:可以理解为linux跟踪打开文件,而分配的一个数字,这个数字有点类似c语言操作文件时候的句柄...
    SkTj阅读 630评论 0 1