在 shell中,输入、输出重定向是很常用的功能。输出重定向,想必大家经常使用。普通的输入重定向,可使用 "<"来实现,例如:
- 参看文件的内容
$ cat < 1.txt
- 按行处理文件
$ while read line; do echo $line; done < 1.txt
除了 "<",还有 "<<"也可以实现输入重定向,并且它有专门的名称,叫作 "Here Documents"。与 "<"不同的是,"<<"可以让你在 shell脚本中实现输入重定向,并指定输入重定向的内容,在这个过程中可以使用脚本中的变量,以及中间处理结果。用法如下:
COMMAND << limit_string
...
documents
...
limit_string
值得注意的是,有些命令是不支持输入重定向的,比如
echo,此时可以用cat实现类似的功能。
在 "<<"后面加上 "-"后,可以让其忽略 documents中行首的 tab缩进,但对其他缩进无效。 "<<-"可用在本身含有缩进块的语句中,例如 "if", "while"等。如下所示:
#!/bin/bash
if true; then
cat << _limit_string
Line 1 with a leading indent.
Line 2 with a leading indent.
Line 3 with a leading indent.
_limit_string
fi
if true; then
cat <<- _limit_string
Line 1 with a leading tab.
Line 2 with a leading tab.
Line 3 with a leading tab.
_limit_string
fi
输出结果为:
Line 1 with a leading indent.
Line 2 with a leading indent.
Line 3 with a leading indent.
Line 1 with a leading tab.
Line 2 with a leading tab.
Line 3 with a leading tab.
参考资料:
950




被折叠的 条评论
为什么被折叠?



