简体   繁体   中英

Echo bash function time in minutes and seconds

somefunc(){
    time (
        sleep 90
    )
}

somefunc

Is there any way to just get minutes.seconds in a variable so I can do something like

somefunc(){
    blah=$(time (
        sleep 90
    ))
    echo "Somefunc finished in $blah"
}

somefunc

Somefunc finished in 1m30s

EDIT

I have the following now:

timeit() { 
    blah="$(TIMEFORMAT='%lU'; time ( $1 $2 $3 ) 2>&1 1>/dev/null)"
    a=$?
    echo "$2 $3 job finished in $blah"
    return $a   
}

timeit /home/blah/script.sh $var1 $var2

In my script I end up calling anywhere from 1 to 30 of this function at the same time in subshells, which runs the script I am using in it, but I am getting the wrong times out of it. they all say 0m0.002s or something like that, only fractions of a second, no seconds or minutes.. Any thoughts?

The output from time goes to STDERR not STDOUT . In order to capture it's value to a variable, you need to do the following:

#!/bin/bash

somefunc() {
    blah="$(TIMEFORMAT='%lU'; time ( $1 ) 2>&1 1>/dev/null)"
    echo "Somefunc finished in $blah"
}

somefunc bleh

You can play with the TIMEFORMAT to get the output you desire.

In Action:

$ cat script.sh
#!/bin/bash

somefunc() {  
    blah="$(TIMEFORMAT='%lU'; time ( $1 ) 2>&1 1>/dev/null)"
    echo "Somefunc finished in $blah"
}

somefunc ls

$ bash script.sh
    Somefunc finished in 0m0.001s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM