#!/bin/bash
# Functions
msg() {
# \e: This is the escape character, which is represented as ^[ in ASCII.
# It signals the terminal to interpret the following characters as an escape sequence.
ALL_OFF="\e[1;0m"
BOLD="\e[1;1m"
GREEN="${BOLD}\e[1;32m"
local mesg=$1; shift
printf "${GREEN}==>${ALL_OFF}${BOLD} ${mesg}${ALL_OFF}\n" "$@" >&2
}
msg "Hello World!"
# ==> Hello World!
: <<COMMENT
#!/bin/bash
# Include the msg function definition here
# Example usage of the msg function
msg "This is a green and bold message."
msg "You can also include variables, like this: %s" "variable_value"
COMMENT
s="AlexLai"
msg "This is a green and bold message."
msg "You can also include variables, like this: %s" $s "variable_value"
# ==> Hello World!
# ==> This is a green and bold message.
# ==> You can also include variables, like this: AlexLai
# ==> You can also include variables, like this: variable_value
The line msg "You can also include variables, like this: %s" $s "variable_value" will call the msg() function twice because of how the arguments are passed and interpreted by the shell. Let me break down why this happens:
msg "You can also include variables, like this: %s" $s "variable_value" is a single command line in Bash.
In this line, you are calling the msg() function with three arguments:
"You can also include variables, like this: %s" (format template).
The value of the variable $s, which is "AlexLai."
The string "variable_value."
The function call starts with msg and its arguments are separated by spaces. Bash interprets this as two separate calls to the msg() function because there are two spaces separating the arguments.
In the first call to msg(), the function receives two arguments:
"You can also include variables, like this: %s" (format template).
The value of the variable $s, which is "AlexLai."
This call prints the formatted message "You can also include variables, like this: AlexLai" and then returns.
In the second call to msg(), the function receives one argument:
The string "variable_value."
This call prints the formatted message "variable_value" and then returns.
So, effectively, the line msg "You can also include variables, like this: %s" $s "variable_value" results in two separate calls to the msg() function, each with different arguments, leading to two separate lines of output. This behavior is due to how Bash tokenizes the command line and passes arguments to functions based on spaces.