Assigning output of a command to variable

When I run

time -p <command>

, it outputs:

real X.XX
user X.XX
sys X.XX

where X.XX is seconds. How I can take just that first number output, the seconds of real time, and assign that to a variable?

Pipe the output to:

awk 'NR==1{print $2;exit}' 

Regards

Edit: to assign the output to a variable:

var=$(time -p <command>|awk 'NR==1{print $2;exit}') 

'time' outputs to stderr by default.

var=$(2>&1 time -p <command>|awk '/real/{print $2;exit}')

Thanks vgersh99, that did it.

I suppose the variable is a string, not an integer. How would I convert this to do some arithmetic operations on it?

typeset -i num=$var

is one way.

However, any variable inside the $(( )) operator that is digits becomes a long integer. (ksh and bash)

a="1"
b="2"
echo $(( a + b )) 
# or this
echo $(( "$a" + "$b" ))

If a were "!" then you get an error, because "!" is not a digit.

I tried this but there seems to be a problem since $var is 1.00, and not just 1. It says error token is ".00". Potentially the string could be any decimal number, so I guess I don't want integers, I want decimal arithmetic. How would I do this?

Most shells don't provide facilities to do floating arithmetics - you have to resort to 'bc':

#!/bin/ksh

a=1.72
b=1.71

sum=$( echo "${a} + ${b}" | bc)

echo "${a} + ${b} = ${sum}"

With bash you can use the TIMEFORMAT variable to control the time shell keyword output:

% t=$({ TIMEFORMAT=%R;time ls>/dev/null;} 2>&1 )
% echo $t
0.046

Thanks again vgersh99.