Search code examples
bashcommand-linemacos-sierra

Create log history excluding some command in bash MacOSX


impossible to find an answer to that: i would like to create a log history of my command line automatically without having to do anything.

For that i found some clues, i modified my .bash_profile but i need to exclude some command that i don't want in my log like "ls, cd, etc." this doesn't work, and i can't d

so here's my code:

# log every command typed and when
command_out=( "more" "less" "cd" "open" "ls" "pwd" "nano" "man" "help") #array of command i don't want to save in my log

my_TEST=0 ##setup a var
FIRST_COMMAND=$(echo $BASH_COMMAND| cut -d' ' -f 1) ##get only the first command 

## test if the first command is in the array
for elm in "${command_out[@]}"; do 
    if [[ $FIRST_COMMAND == $elm ]]; then
echo $elm # does not work
        $my_TEST=1 ## if the command is in the array the var is setup to 1
    fi
done


if [[ $my_TEST == 0 ]] && [ -n "${BASH_VERSION}" ]; then
    trap "caller >/dev/null || \
printf '%s\\n' \"\$(date '+%Y-%m-%dT%H:%M:%S%z')\
 \$(tty) \${BASH_COMMAND}\" 2>/dev/null >>~/.command_log" DEBUG
fi

if you any other ideas of how to do what i want i'm open

Thanks you


Solution

  • Bash automatically keeps a history of every command you type; you can use the history command to view it. If you want to exclude certain commands, rather than trying to exclude them from the log, I would skip them when viewing it, e.g. history | egrep -vw 'ls|cd|other|commands|here'.

    You can set HISTTIMEFORMAT to get a timestamp with every entry, control how many commands are kept with HISTFILESIZE, and if you really want to keep some commands out instead of just not seeing them when you look, you can list them in HISTIGNORE. See https://www.gnu.org/software/bash/manual/html_node/Using-History-Interactively.html.