Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

I want to log every time I run a certain type of command in the terminal. For example, every time I run:

sudo apt-get install [something]

I want to add [something] to a log file in my home directory that will look like the following:

[timestamp] [something]
2012-10-02 mysql-server
2012-10-03 ruby1.9.1
2012-10-06 gedit-plugins
2012-10-07 gnome-panel synaptic

What's the easiest way to make this happen automatically?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

The most straightforward way to do this would be to replace apt-get with a wrapper script which would log the data into a logfile and then invoke apt-get passing it all the parameters the wrapping script received (and returning the return code the original program returned).

If you're careful to mimic the behaviour of the original command very closely, nobody would notice any difference.

share|improve this answer

Note that any use of sudo on the system will already be logged in /var/log/auth.log. That file also contains other authorization-related information (see more details here about log files).

Sudo also logs more than just the timestamp, but also the user who invoked sudo, the working directory, and more. If you want to just extract the uses of apt-get install and only log the package name, this would do it:

grep "apt-get install" /var/log/auth.log | awk  '{print $1 " " $2 " " $16}'

I don't know if the formatting of the date is important to you, I didn't bother since including that in the commandline above would have made it longer and less readable. But if you want have a longer bash script which converts the format, date -I -d "Apr 27" will convert it for you.

(By the way, your user must be a member of the adm group in order to read /var/log/auth.log. If you see Permission denied then you may need to prepend the grep command with sudo, or add yourself to the group with sudo addgroup USERNAME adm where USERNAME is your user name.)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.