shell 中 “Here-Documents“ 的基本用法

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.

参考资料:

  1. https://www.howtogeek.com/719058/how-to-use-here-documents-in-bash-on-linux/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值