Issue
test.sh
COMMAND1="Build `date`"
COMMAND2="echo $PATH"
echo "Command1 is: $COMMAND1"
echo "Command2 is: $COMMAND2"
output
Command1 is: Build Wed Dec 26 21:09:43 UTC 2018
Command2 is: echo /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
In above shell script, how can I echo without evaluating the expressions i.e. I want Command1 is: Build `date`
I understand I can escape the `
and the $
character, but in my application they are coming from an upstream service and passed as an argument to the shell script. Even the upstream service cannot escape them because later in script I actually need to execute these commands.
The ideal way would be to tell echo to only expand the variable $COMMAND1
, but do not evaluate anything inside it. Or use sed
to escape all occurrences of `
and $
, but I haven't been able to achieve either.
Solution
The expression is evaluated on assignment.
COMMAND1="Build `date`"
The `...`
is a command substitution and is deprecated in favor of $( ... )
style. The "
doublequotes are used to allow the text to be expanded. So first this command is expanded to:
COMMAND1='Build Wed Dec 26 21:09:43 UTC 2018'
Then the assignment happens. You can't retrieve later what command was used to declare the variable. That information is lost. If you have some upstream - it needs to pass this information to you along.
If you wish for COMMAND1
to contain the string (literally)
Build `date`
You can use single quotes:
COMMAND1='Build `date`'
You can later use some combination of eval
or similar to expand the variable, however I would suggest to just do a function
COMMAND1() {
Build $(date)
}
echo "COMMAND1 is declared as:"
declare -f COMMAND1
echo "COMMAND1 execution returns: $(COMMAND1)"
Helpful links:
Answered By - KamilCuk Answer Checked By - Clifford M. (WPSolving Volunteer)