I've got a script that calls Perl's Time::HiRes module to calculate elapsed time. Basically the script gets the time by passing the following one-liner:
use Time::HiRes qw(time); print time
to the Perl interpreter via back ticks and gets back the results.
#/bin/sh
START_TIME=`perl -e 'use Time::HiRes qw(time); print time'`
END_TIME=`perl -e 'use Time::HiRes qw(time); print time'`
ELAPSED_TIME=$(echo "($END_TIME - $START_TIME)" | bc)
echo $ELAPSED_TIME
I tried to rewrite it in a more modular way but I'm stumped by the quoting rules of the bash shell.
#/bin/sh
CALCULATE='bc'
NOW="perl -e 'use Time::HiRes qw(time); print time'"
START_TIME=`$NOW`
[Some long running task ...]
ELAPSED_TIME=$(echo "($NOW - $START_TIME)" | $CALCULATE)
echo $ELAPSED_TIME
Bash complains that something is not quoted properly. Why doesn't bash just expand the command in $NOW and pass it to the back tick to be executed?
I tried various ways to embed perl code in a shell script variable but can't seem to get it right.
Anyone knows how to quote perl code inside a shell script correctly?
perl -MTime::HiRes=time -e 'print time'
– glenn jackman Apr 28 '12 at 11:34