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!

  • Is this what you want as output date -d "12:48:03 today + 10 seconds" +'%H:%M:%S' – Rakholiya Jenish Jun 21 '15 at 17:08
  • Yup, that's it exactly. – evamvid Jun 21 '15 at 17:13

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
  • echoing this gives the output that I want, but now how do I execute the command stored in the CALL variable now? I tried calling it with a line consisting of just $CALL, but the date command gave an error; extra operand "+". I'm not sure if this is a problem with bash or with the command itself, but I'm pretty sure I constructed the command correctly. – evamvid Jun 22 '15 at 0:53
  • 1
    To execute $CALL do eval $CALL. You dont need ("). – meuh Jun 22 '15 at 5:24

You can edit your call statement as:

CALL="$(echo date -d \"$ENDTIME\" +\'%H:%M:%S\')"

The \ can be used to escape the characters " and '. Now echo $CALL will output as:

date -d "22:46:37 today + 10 seconds" +'%H:%M:%S'

Put single quotes inside your double-quoted ENDTIME variable, like so:

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

It should give

date -d '19:35:28 today + 10 seconds' +%H:%M:%S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.