【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

你可能感兴趣的:(【shell】脚本读取输入重定向(<)文件)