Handling multi-line strings in Bash is a common task, especially when writing scripts to manage configuration files or generate reports. Using multi-line strings with variables makes scripts more dynamic and flexible. Below, I will demonstrate with a specific example how to use multi-line strings with variables in Bash scripts.
Suppose we need to create a configuration file that contains dynamically generated content, such as the username and server address. We can achieve this using Bash's "heredoc" syntax.
Example
bash#!/bin/bash # Define variables USERNAME="xiaoming" SERVER="server.example.com" # Use heredoc to create multi-line strings cat <<EOF > config.txt Hello, $USERNAME! Welcome to $SERVER. This is your configuration file. # Additional configuration items can be placed here EOF echo "Configuration file generated."
Explanation
-
Variable Definition:
- The
USERNAMEandSERVERvariables are defined and assigned corresponding values.
- The
-
Heredoc:
- The
<<EOFstarts the multi-line string input, ending when a singleEOFline is encountered. - Within this multi-line string, we can directly use Bash variables, such as
$USERNAMEand$SERVER. > config.txtindicates redirecting the heredoc content to theconfig.txtfile.
- The
-
File Output:
- The generated
config.txtfile contains the multi-line text with variable substitutions, maintaining the expected format. - The script outputs a message indicating that the configuration file has been generated.
- The generated
In this way, we can flexibly handle multi-line strings with variables in Bash scripts, making them more flexible and useful. This technique is very useful in scenarios such as automated configuration management and report generation.