Dreamk33
Dreamk33

Reputation: 247

How to get the output of time command in a bash script?

This command work perfectly in my shell and I want to write it inside a bash script but it doesn't work anymore :

make -s clean > /dev/null; { time make -j -s gallery > /dev/null; } 2>&1 | grep real | sed 's/^.*m//;s/.$/ /' > time_make 

The problem is the outpout of time.

In the shell this commande :

make -s clean > /dev/null; { time make -j 1 -s gallery > /dev/null; } 2>&1 | grep m > time_make

has for result :

real   0m2.127s
user   0m3.375s
sys    0m0.532s

That's good.

But in the script (#! /bin/sh):

The same command has for result :

3.36user 0.51system 0:02.08elapsed 186%CPU (0avgtext+0avgdata49100maxresident)k
0inputs+2384outputs (0major+114980minor)pagefaults 0swaps

How to get the value of "real" in the bash script?

I really don't understand why it's not the same output for the "time" command. Could anyone help me please?

Thanks in advance.

Upvotes: 1

Views: 844

Answers (1)

Julian
Julian

Reputation: 2907

If you want to capture the time a command takes in bash, you can get a lot more control by doing something like this (assumes you're on a system with GNU time installed):

START=$(date +%s.%N)
# command you want to time goes here
END=$(date +%s.%N)
printf -v DELTA "%g" $(bc <<<"$END - $START")
echo "Command took ${DELTA} seconds"

You can actually format the output into hours, minutes, seconds etc.

Upvotes: 1

Related Questions