Bash – In bash, how to call a variable and wrap quotes around its value as part of a command without causing the variable name to become a string literal

bashdatequotingshell-script

So I want to add 10 seconds to a time. The command to do that came from here.

To illustrate:

STARTIME="$(date +"%T")"
ENDTIME="$STARTIME today + 10 seconds"
CALL="$(echo date -d $ENDTIME +'%H:%M:%S')"

The problem that I have with this code is that if I echo the $CALL variable, it gives:

date -d 12:51:19 today + 10 seconds +%H:%M:%S

The correct version of this string would look like:

date -d "12:48:03 today + 10 seconds" +'%H:%M:%S'

But if I wrap the variable name in quotes, like so:

STARTIME="$(date +"%T")"
ENDTIME="$STARTIME today + 10 seconds"
CALL="$(echo date -d '$ENDTIME' +'%H:%M:%S')"

…it's interpreted as a string literal, and if you echo it, it gives:

date -d $ENDTIME +%H:%M:%S

So what I need to do is call the variable such that it's value is swapped into the function and wrapped with double-quotes("), but avoid the name of the variable being read as a literal string. I'm extremely confused with this, I miss Python!

Best Answer

Just for completeness, you don't need all those (") nor the final $(echo ...). Here's the simplified version of your assignments that produce the same effect:

STARTIME=$(date +"%T")
ENDTIME="$STARTIME today + 10 seconds"
CALL="date -d '$ENDTIME' +'%H:%M:%S'"

Note how you don't need to quote when doing var=$(...) but you do usually with var="many words":

a=$(echo 'a    b'); echo "$a" # result: a    b

Inside (") a (') has no special significance, and vice-versa, eg:

a="that's nice"; echo "$a" # result: that's nice
a='that "is nice'; echo "$a" # result: that "is nice
Related Question