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. Commented 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. Commented 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).

Sign up to request clarification or add additional context in comments.

4 Comments

is it going to impact general system performance if I put trap debug in /etc/bashrc?
Not really, I have even used trap debug and PROMPT_COMMAND together.
Ok. When I connect to the server I see some commands from others scripts (~/.bashrc, ..) it there a way to ignore those scripts. thanks
So do you just want to store each and every executed command in a file?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.