1

Can someone please explain why this doesn't work? I have a bash function that simply returns the number of seconds in a duration timestamp.

Shell script function

seconds() { 
    result=$(echo "\"1970-01-01 $1+0\"")
    echo date +%s -d $result
}

Calling the function

seconds 00:00:02.00 #works

Produces the following output date +%s -d "1970-01-01 00:00:02.00+0" if I copy this exact text and execute it in the terminal it works.

$(seconds 00:00:02.00) #error

However this returns an error:

date: extra operand ‘00:00:02.00+0"’

What's the problem here? Or is there a better way to do this?

1 Answers1

2

You don't need to use echo at any point here.

Using the subshell, you're executing the output of the seconds function which is generally ill-advised as it can cause unexpected behavior like you're seeing.

Instead, simplify your function to run the date command itself:

#!/bin/bash
seconds () {
    date -d "1970-01-01 $1+0" "+%s"
}

seconds 00:00:02.00

Output: 2

John Moon
  • 1,013
  • 2
    Small note that what the OP is using is command substitution vice subshell. A thorough explanation of what John is saying can be found here: https://unix.stackexchange.com/a/213544/151609 – Jeff May 01 '18 at 05:24