Shell - Here Document

Bash Here Document (Heredoc)

A Here Document (Heredoc) in Bash is a type of redirection that allows you to pass multiple lines of input to a command. It is particularly useful when you need to pass a multiline block of text or code to an interactive command, such as cat, tee, or sftp.

Basic Syntax and Usage

The basic syntax for a Heredoc is as follows:

[COMMAND] <<[-] 'DELIMITER'

Line 1

Line 2

DELIMITER

COMMAND: This is optional and can be any command that accepts redirection.

<<: The redirection operator.

DELIMITER: A string that marks the end of the Heredoc. Common delimiters are EOF, END, etc.

[-]: Adding a dash suppresses leading tab characters, allowing for indentation.

Example with cat

cat << EOF

Hello

World

EOF

This will output:

Hello

World

Variable and Command Expansion

Heredocs can include variables and commands which will be expanded:

var1="Hello"

var2="World"

cat << END

$var1

$var2

$PWD

END

This will output the values of var1, var2, and the current working directory.

Ignoring Expansion

To ignore variable and command expansion, quote the delimiter:

cat << "EOF"

$(echo Hello)

$(whoami)

$PWD

EOF

This will output the literal text without expansion.

Advanced Usage

Redirecting Output to a File

You can redirect the output of a Heredoc to a file:

cat << EOF > hello_world.txt

Hello

World

EOF

This will create a file hello_world.txt with the content:

Hello

World

Piping Output

You can pipe the output of a Heredoc to another command:

cat << EOF | sed 's/l/e/g'

Hello

World

EOF

This will output:

Heeeo

Wored

Using Heredoc with SSH

Heredocs can be used to execute multiple commands on a remote system over SSH:

ssh user@host << EOF

echo "Local user: $USER"

echo "Remote user: \\$USER"

EOF

This will print the local and remote users.

Functions and Heredoc

You can pass parameters to a function using a Heredoc:

readLines(){

read greeting

read name

}

readLines << EOF

Hello

$USER

EOF

echo $greeting

echo $name

This will output:

Hello

<your-username>

Conclusion

Heredocs are a powerful feature in Bash scripting, allowing for the inclusion of multiline text and commands in a clean and readable manner. They are especially useful for automating tasks and executing commands on remote systems.

参考阅读:

Here Documents

Here Documents

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夜流冰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值