I'd like to get the last command used and its execution time. This will be used as part of an alias for notification.
Ubuntu – Last command and execution time
command linenotification
Related Question
- Ubuntu – How to measure the execution time of a terminal process
- Ubuntu – Using last part of command for next command
- Ubuntu – Use of default alias “alert”
- Ubuntu – Go back to the last command
- Ubuntu – Notify-send and terminal command
- Ubuntu – Using time -v to calculate execution time. Command not found
- Ubuntu – Measuring execution time of a command in milliseconds
Best Answer
NOTE: I'm assuming
bash
as the shell.Adapting to other shells shouldn't be difficult.
Getting the last command used is trivial: it's stored in the shell event designator
!!
, and can also be obtained using the shell builtinsfc
(fc -s
) orhistory
(with some string manuipluation:history 1 | awk '{$1=""}1'
).Getting the time of execution, or the running time, however, is not, unless some action is taken before the command has executed. Once the command is run, nothing can be done - the horses have bolted.
For getting the time of execution, either:
HISTTIMEFORMAT
variable, which would makebash
save the time of execution in the history, then use text processing to extract the time from the output ofhistory
.For getting the running time, again, either:
HISTTIMEFORMAT
before running the command, you could parse the output ofhistory
to get the execution time and then calculate the run time.time
:time some-command
. Processing the output oftime
is a bit messy if you want to leave the output of the command untouched.With
HISTTIMEFORMAT
setIf you set the
HISTTIMEFORMAT
variable, then you need not use a wrapper. First, in your.bashrc
, setHISTTIMEFORMAT
. You can set it to anything, as long as it's not empty. If you don't want yourhistory
command to show the time, you could set it to a space (HISTTIMEFORMAT=" "
).Now, there's an alias present in the default
.bashrc
of Ubuntu:We can adapt it for our purposes:
You can use it thus:
Wrapper function
Using a function or a script to wrap around the command:
Then run your command prefixed with
a
:Notes:
$SECONDS
special variable and thedate
command. You could get by with only thedate
command.notify-usd
, which should be available on standard Ubuntu. You could look at other ways of producing notifications.$RET
and returned it, so you should be able to rely on exit codes:do-something; a || echo "Couldn't do something."
ora do-something || echo "Couldn't do something."
willecho
ifdo-something
had a non-zero exit status.