2

I'm looking for a bash script that can parse a time duration.

If three arguments are given, they represent hours, minutes, and seconds. If two arguments are given, they represent minutes and seconds, with the hours zero.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Camel
  • 21
  • 2

3 Answers3

4

What about the following:

#!/bin/bash

h=0
if [ "$#" -ge 3 ]
then
   h=$1
   shift
fi
sec=$((3600*$h+60*$1+$2))

echo "The total number of seconds is $sec"

Since the question does not specify what you aim to do with the given time, the program calculates the total number of seconds. Furthermore perhaps it is useful to do a check if at least two arguments are given.

The script uses the shift operation, the shift makes makes $1 := $2; $2 := $3, etc. In other words, the first argument is processed, and then you "pretend" it never existed.

By default you set h to zero, and only if the number of arguments is greater than or equal to 3, it will set h.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
2

This is a more or less general solution for that type of task. Sorry, if it is a monkeycode, but I think it is sufficient:

gettime() {
    params=(
        years months weeks days hours minutes seconds
    )
    for i in `seq ${#params}`; do
        param_i=$((${#params} - i + 1)) # reversed params index
        [ $i -le $# ] && {
            eval "local ${params[$param_i]}=\$$(($# - i + 1))"
        } || {
            eval "local ${params[$param_i]}=0"
        }
        eval "echo ${params[$param_i]} '==' \$${params[$param_i]}" # debug output
    done
}

Here's the sample output:

$ gettime 3 4 5 6 7

seconds == 7
minutes == 6
hours == 5
days == 4
weeks == 3
months == 0
years == 0

Note, that the shell you are using must be not only support POSIX standards, but also arrays.

theoden8
  • 773
  • 7
  • 16
0

First Argument: $1

Second Argument: $2

Third Argument: $3

and so on...

Example:

bash-2.05a$ ./parseDuration.sh 13 25 25
13 hours and 25 minutes and 25 seconds
bash-2.05a$ cat ./parseDuration.sh
#!/bin/bash
echo "$1 hours and $2 minutes and $3 seconds"
  • I think the OP means that if two arguments are given, that the first and second are interpreted as minutes and seconds respectively. – Willem Van Onsem Sep 18 '15 at 23:34
  • Thanks for the reply. So how do I normalize. for instance we do not say "two minutes and sixty-five seconds". rather, we say "three minutes and five seconds. Basically, how can I overflow the value to the next higher unit. The renge is 00-59. – Camel Sep 18 '15 at 23:37