Use 'heredoc' in shell scripts

64 篇文章 1 订阅
24 篇文章 0 订阅
Linux users who work with large blocks of text may want to consider using heredoc. Find out how to use heredoc in a single statement to print many lines of text in a shell script. 

A lesser-known feature of shell scripting is "here documents" or heredoc. Basically, heredoc is a mechanism for working with large blocks of text. From a readability standpoint, heredoc is extremely useful. The code is easy to read, easy to work with, and very straightforward.

Heredoc is especially handy when you want to use a single statement to print many lines of text. For example, assume you have written a script to automatically generate an e-mail message. You might first write the text of the message to a temporary file, and then use the system MTA to send it:

echo "From: $from" >>$tmpfile
echo "To: $to" >>$tmpfile
echo "" >>$tmpfile
echo "This is the first line of text." >>$tmpfile
echo "This is the second line of text." >>$tmpfile

This is cumbersome and difficult to read, and it's certainly more difficult than it should be to manipulate. Contrast that with the following heredoc style:

cat <<EOT >$tmpfile
From: $from
To: $to

This is the first line of text.
This is the second line of text.
EOT

In this snippet, the cat command is used to print out a block of text. The <<EOT string indicates that everything following is to be treated as input until the string EOT is reached. You can use any string that you like, but the terminating string must be at the beginning of the line, so don't indent it with any tabs or white spaces. You can also make use of any variables previously defined; in this case, the $from and $to variables would have been set in the script before they were used in the heredoc statement.

To print this block of text to the terminal, omit the redirector that was used (>$tmpfile), which redirected the output to the file specified by the variable $tmpfile. If you omit that redirection, the text will print to the screen.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值