Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Delayed execution when using bash's trap command?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 \\$ "
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading