Capture last command In bash

For whatever reason you may want to save the last command you wrote. Heres a way to do so.

trap 'previous=$this_command; this_command=$BASH_COMMAND' DEBUG
    
echo "Hello"

#This line removes the trap you just set. 
#If you don't remove this trap, 
#it will continue to override "previous"

trap - DEBUG

#now lets echo out $previous

echo $previous;

exit;

this command allows you to only capture commands that through an error

trap "command=$BASH_COMMAND" ERR

Leave a Reply

Your email address will not be published.