3

Is there a way to produce a custom activity log in my BASH shell? It would save, in each row, the last command, the time when it was run, and the working directory from which it was run.

Note: It doesn't need to use exec, but I don't have root access to the shell, my idea was to limit just how much people should assume I can use. I suggested exec because it felt like a good solution.

  • It won't solve the working directory part, but you can set HISTTIMEFORMAT to get timestamp logging in bash history. – Wildcard Jun 3 at 20:34
2

One might set PROMPT_COMMAND to accomplish this goal as follows or in a myriad of other ways.

export PROMPT_COMMAND='echo -e $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//")\\t$(date)\\t$(pwd) >> $HOME/history.csv'

The file could be opened as a CSV file with a custom field separator (TAB). The character is produced with the -e switch to the builtin echo command which "enable[s] interpretation of backslash escapes."

  • $(history 1 | sed "s/^[ ]*[0-9]\+[ ]*//") : In Linux, get the last command w/o command number, and w/o white space surrounding the command number.
  • $(date): Get the current date and time.
  • $(pwd): Get the current working directory.
  • >> $HOME/history.csv: Append (>>) the output to a file.

This produces output such as the following line, if ls -la were executed from $HOME (of username).

ls -la    Tue May 14 12:00:36 EDT 2019    /home/username
  • Thanks, Chris. Looks promising. I'll take a look later. – Wrapper May 14 at 17:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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