There’s no need to use fc
if you just need the current command line, as the shell variable BASH_COMMAND
holds exactly that. I’d just trap the DEBUG
signal and use this variable as before, e.g.:
trap 'echo "$USER":"$BASH_COMMAND" >>/path/to/log' DEBUG
This also has the advantage that it doesn’t write anything to the log if you just press Enter – fc
just reads the last entry from the history list. Unfortunately I wasn’t able to test your logger
command on my system, but you sound like it worked fine, so this should work as well:
trap 'logger -p local1.notice -t bash -i -- "$USER":"$BASH_COMMAND"' DEBUG
Example run
Note how alias
es like ls
, empty lines (Enter) and typo’d commands are logged.
$ trap 'echo "$USER":"$BASH_COMMAND" >>/path/to/log' DEBUG
$ uname
Linux
$ pwd
/home/dessert
$ hostname
dessert’s plowhorse
$ ls
dir1 file1 file2
$
$
$ bahs
No command 'bahs' found, did you mean:
Command 'bash' from package 'bash' (main)
Command 'bats' from package 'bats' (universe)
bahs: command not found
$ cat /path/to/log
dessert:uname
dessert:pwd
dessert:hostname
dessert:ls --color=auto
dessert:bahs
dessert:cat /path/to/log
DEBUG
trap and inPROMPT_COMMAND
? That would mean you're logging double anyway. – muru Jun 8 '18 at 3:56