6

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!

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

3 Answers 3

9

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
2
  • 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
    Commented Jun 22, 2015 at 0:53
  • 1
    To execute $CALL do eval $CALL. You dont need (").
    – meuh
    Commented Jun 22, 2015 at 5:24
3

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'
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .