1

I am trying to code a script to log all commands executed on a server, currently I have 2 versions:

(simplified version of the scripts)

Version 1:

function fc
{
  fc -ln -0
}
trap fc DEBUG

Version 2:

function fc
{
 cmd=`fc -ln -0`
 echo $cmd
}
trap fc DEBUG

The script is inluded in /etc/bash.bashrc : source script.sh

The problem is that when I run this scripts I don't get the same result:

When I run the first verion I get the command that triggered the trap :

SERVER#
SERVER#
SERVER# test
SERVER# ls
ls

But when I run the second I get the last-1 command :

SERVER#
SERVER#
SERVER# test
SERVER# ls
test

Thanks in advance.

2
  • 5
    In the 2nd version, you're executing fc in a different process, so you won't have the same history. Jan 6, 2015 at 16:43
  • @glennjackman Thanks, I have tried to run this directly in bash cmd=fc -ln -0; echo $cmd and cmd=fc -ln -0`, I had the same result.
    – ob_dev
    Jan 7, 2015 at 14:53

1 Answer 1

1

If you're using a function for trap DEBUG then you can make use of special BASH variable BASH_COMMAND.

dbg() { echo "$BASH_COMMAND" >> ~/cmd.log }

trap 'dbg' DEBUG

Make sure this trap command is very last line in your ~/.bashrc (or last line in ~/.bash_profile, if that exists).

4
  • is it going to impact general system performance if I put trap debug in /etc/bashrc?
    – ob_dev
    Jan 7, 2015 at 10:14
  • Not really, I have even used trap debug and PROMPT_COMMAND together.
    – anubhava
    Jan 7, 2015 at 11:15
  • Ok. When I connect to the server I see some commands from others scripts (~/.bashrc, ..) it there a way to ignore those scripts. thanks
    – ob_dev
    Jan 7, 2015 at 11:27
  • So do you just want to store each and every executed command in a file?
    – anubhava
    Jan 7, 2015 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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