Is there a way to intercept every command given to bash? I can intercept a particular command, e.g., cd by defining a function cd() and I can do that for one-command-at-a-time for other commands as well. But can I write a function which gets called before every command is executed? I want to do some bookkeeping of commands, and then executed the command.
Michał Šrajer's idea PS4='$(echo $(date) $(history 1) >> /tmp/trace.txt) TRACE: ' looks very promising but here is the output I get:
$ ping www.google.com
TRACE: ping www.google.com
PING www.l.google.com (74.125.224.52) 56(84) bytes of data.
64 bytes from 74.125.224.52: icmp_seq=1 ttl=56 time=3.77 ms
64 bytes from 74.125.224.52: icmp_seq=2 ttl=56 time=2.33 ms
^C
--- www.l.google.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 2.334/3.054/3.774/0.720 ms
TRACE: echo -ne '\033]0;myhost.com /home/yogeshwer/github/myproject\007'
TRACE: grep -e '\* '
TRACE: git branch
TRACE: sed 's/^..\(.*\)/ {\1}/'
And Wed Aug 3 12:47:27 PDT 2011 6672 ping www.google.com get written in /tmp/trace.txt exactly 5 times. The four other ones comes from my definition of PS1 where I run the following command: $(git branch 2> /dev/null | grep -e "\* " | sed "s/^..\(.*\)/ {\1}/"). Two questions:
- Is it possible to write the command to
/tmp/trace.txtexactly? - And more importantly, is it possible to not clutter the output of the command, but only write the command to
/tmp/trace.txt?
I am so excited about the possibility of being able to record commands from all my bash sessions in one place!
.bash_historyis not sufficient for your needs, I take it? – Andrew Aug 3 '11 at 17:27.bash_historyis updated only when the shell exits. – Keith Thompson Aug 3 '11 at 17:36.bash_historyis not sufficient.PROMPT_COMMANDis executed just before the command is executed (I think), but I don't have access to "command about to be executed" whenPROMPT_COMMANDis executed. What will be perfect is to grab the command "about to be executed next", do some statistics on it (how many times it has been executed etc) and write that to some log file, and then actually execute the command. – Yogeshwer Sharma Aug 3 '11 at 19:24