I use the following .bashrc code to display execution times per command:
ps1_starttime() { PS1_STARTTIME=$EPOCHREALTIME ; }
ps1_duration() { printf "%0.3f" $(bc <<< "$EPOCHREALTIME- $PS1_STARTTIME") ; }
trap "ps1_starttime" DEBUG
export PS1="\`ps1_duration\` \w \\$ "
This works, but I would like to directly inline the ps1_starttime function into the trap statement:
trap 'PS1_STARTTIME=$EPOCHREALTIME' DEBUG
When I do this, $EPOCHREALTIME is evaluated immediately and as a result is not re-evaluated per command as needed.
How to inline the variable assignment directly in trap without the need for an extra function?
>Solution :
Use a subshell to delay the evaluation of $EPOCHREALTIME. This way, it will be evaluated each time the trap is triggered.
trap 'PS1_STARTTIME=$(echo $EPOCHREALTIME)' DEBUG
export PS1="\$(printf '%0.3f' \$(bc <<< \"\$EPOCHREALTIME - \$PS1_STARTTIME\")) \w \\$ "