Please see below code which will redirect into a variable and different options by which you can achieve it:
Option 1:
# !/usr/bin/bash
var=`(time (sleep 5)) 2>&1 | grep real`
Output:
real 0m5.069s
You can execute your script inside it as below :
# !/usr/bin/bash
var=`(time sh ./yourscript.sh) 2>&1 | grep real`
Option 2: Get time taken by the script to execute
# !/usr/bin/bash
start=$(date +%s)
# Execute another script
sh ./yourscript.sh
end=$(date +%s)
diff=$(( $end- $start))
echo "It took $diff seconds"
Output : It took 5 seconds
Option 3:
# !/usr/bin/bash
#var=$( TIMEFORMAT="%R"; { time (sleep 5); } 2>&1 )
var=$( TIMEFORMAT="%R"; { time sh ./yourscript.sh; } 2>&1 )
Based on good feedback of @Charles Duffy: Changed some parts and
If targeting bash 4.3 or later, consider printf -v start '%(%s)T' -1
as a much more efficient alternative to start=$(date +%s)
.