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