Getting a "numeric argument" when running a script with arithmetic operations

I am trying to write a function that should convert a timestamp of the form hr: min: sec, ms (i.e. 15: 41: 47,757) into milliseconds. The function is as follows:

#!/bin/sh
mili () {

    hr=$(echo "$1" | cut -c1-2)
    echo "hr is: " $hr
    min=$(echo "$1" | cut -c4-5)
    echo "min is: " $min
    sec=$(echo "$1" | cut -c7-8)
    echo "sec is: " $sec
    ms=$(echo "$1" | cut -c10-12)
    echo "ms is: " $ms
    total=$(($hr \* 3600 + $min \* 60 + $sec) \* 1000 + $ms)

    return "$total"
    #echo "Result is: "$total" "
}

mili $1

However, when I run it:

./mili.sh "15: 41: 47,757"

I get the following message:

./mili.sh: command substitution: line 15: syntax error near unexpected token 
`\*'
./mili.sh: command substitution: line 15: `($hr \* 3600 + $min \* 60 + $sec) 
\* 1000 + $ms'
./mili.sh: line 17: return: : numeric argument required

I tried expr options with and without single quotes, double quotes, and writebacks, but could never get it to calculate arithmetic. I can confirm a simple command how it works: expr 2 * 3, but when I try to use something like this in my script, it fails.

How can I make it just evaluate my expression?

+4
source share
3

* . , . , :

total=$(($hr \* 3600 + $min \* 60 + $sec) \* 1000 + $ms)

total=$((($hr * 3600 + $min * 60 + $sec) * 1000 + $ms))

Alternative

, cut:

mili() {
    IFS=':,' read hr min sec ms <<<"$1"
    echo "hr is: " $hr
    echo "min is: " $min
    echo "sec is: " $sec
    echo "ms is: " $ms
    total=$((($hr * 3600 + $min * 60 + $sec) * 1000 + $ms))
    echo "Total=$total"
    return "$total"
}

: Bash

Bash . :

$ a=1; echo "$((1 + a)) and $((1+ $a))"
2 and 2

$ , . Chepner , undefined :

$ unset a
$ echo $((1 + $a))
bash: 1 + : syntax error: operand expected (error token is "+ ")
$ echo $((1 + a))
1

:

  • , undefined , $.

  • , undefined , , , $.

mili undefined hr, min .. , , , $. , , $ .

+4

:

  • return "$total": int 0 255. echo "$total"

  • , // 08 09 - bash , , 8 9 - .

    $ mili 11:22:09,456
    hr is:  11
    min is:  22
    sec is:  09
    ms is:  456
    bash: (11 * 3600 + 22 * 60 + 09: value too great for base (error token is "09")
    

:

mili () {     
    IFS=":,." read -r hr min sec ms <<<"$1"
    echo "hr is:   $hr" >&2
    echo "min is:  $min" >&2
    echo "sec is:  $sec" >&2
    echo "ms is:  $ms" >&2
    echo "$(( ((10#$hr * 60 + 10#$min) * 60 + 10#$sec) * 1000 + 10#$ms ))"
}

10# -10

$ ms=$(mili 11:22:09.456)
hr is:   11
min is:  22
sec is:  09
ms is:  456

$ echo $ms
40929456
+3

Here is a crazy alternative:

$ mili () {
    IFS=., read -r time ms <<<"$1"
    ms3=$(cut -c 1-3 <<<"${ms}000")
    echo "$(date -u -d "1970-01-01 $time" +%s)$ms3"
}

$ mili 15:41:47,757
56507757

$ mili 15:41:47,75
56507750

$ mili 15:41:47
56507000
+1
source

Source: https://habr.com/ru/post/1683996/


All Articles