Prevent duplicates from being saved in bash history [closed] - bash

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I'm trying to prevent bash from saving duplicate commands to my history. Here's what I've got:
shopt -s histappend
export HISTIGNORE='&:ls:cd ~:cd ..:[bf]g:exit:h:history'
export HISTCONTROL=erasedups
export PROMPT_COMMAND='history -a'
This works fine while I'm logged in and .bash_history is in memory. For example:
$ history
1 vi .bashrc
2 vi .alias
3 cd /cygdrive
4 cd ~jplemme
5 vi .bashrc
6 vi .alias
$ vi .bashrc
$ history
1 vi .alias
2 cd /cygdrive
3 cd ~jplemme
4 vi .alias
5 vi .bashrc
$ vi .alias
$ history
1 cd /cygdrive
2 cd ~jplemme
3 vi .bashrc
4 vi .alias
$ exit
But when I log back in, my history file looks like this:
$ history
1 vi .bashrc
2 vi .alias
3 cd /cygdrive
4 cd ~jplemme
5 vi .bashrc
6 vi .alias
7 vi .bashrc
8 vi .alias
What am I doing wrong?
EDIT: Removing the shopt and PROMPT_COMMAND lines from .bashrc does not fix the problem.

As far as I know, it is not possible to do what you want. I see this as a bug in bash's history processing that could be improved.
export HISTCONTROL=ignoreboth:erasedups # no duplicate entries
shopt -s histappend # append history file
export PROMPT_COMMAND="history -a" # update histfile after every command
This will keep the in memory history unique, but while it does saves history from multiple sessions into the same file, it doesn't keep the history in the file itself unique. history -a will write the new command to the file unless it's the same as the one immediately before it. It will not do a full de-duplication like the erasedups setting does in memory.
To see this silliness in action, start a new terminal session, examine the history, and you'll see repeated entries, say ls. Now run the ls command, and all the duplicated ls will be removed from the history in memory, leaving only the last one. The in memory history becomes shorter as you run commands that are duplicated in the history file, yet the history file itself continues to grow.
I use my own script to clean up the history file on demand.
# remove duplicates while preserving input order
function dedup {
awk '! x[$0]++' $#
}
# removes $HISTIGNORE commands from input
function remove_histignore {
if [ -n "$HISTIGNORE" ]; then
# replace : with |, then * with .*
local IGNORE_PAT=`echo "$HISTIGNORE" | sed s/\:/\|/g | sed s/\*/\.\*/g`
# negated grep removes matches
grep -vx "$IGNORE_PAT" $#
else
cat $#
fi
}
# clean up the history file by remove duplicates and commands matching
# $HISTIGNORE entries
function history_cleanup {
local HISTFILE_SRC=~/.bash_history
local HISTFILE_DST=/tmp/.$USER.bash_history.clean
if [ -f $HISTFILE_SRC ]; then
\cp $HISTFILE_SRC $HISTFILE_SRC.backup
dedup $HISTFILE_SRC | remove_histignore >| $HISTFILE_DST
\mv $HISTFILE_DST $HISTFILE_SRC
chmod go-r $HISTFILE_SRC
history -c
history -r
fi
}
I'd love to hear more elegant ways to do this.
Note: the script won't work if you enable timestamp in history via HISTTIMEFORMAT.
Bash can improve the situation by
fix history -a to only write new data if it does not match any history in memory, not just the last one.
de-deduplicate history when files are read if erasedups setting is set . A simple history -w in a new terminal would then clean up the history file instead of the silly script above.

The problem is definitely the histappend. Tested and confirmed on my system.
My relevant environment is:
$ set | grep HIST
HISTFILE=/Users/hop/.bash_history
HISTFILESIZE=500
HISTIGNORE=' *:&:?:??'
HISTSIZE=500
$ export HISTCONTROL=erasedups
$ shopt | grep hist
cmdhist on
histappend off
histreedit off
histverify off
lithist off
Now that I think about it, the problem is probably with the history -a. history -w should write the current history without any duplicates, so use that if you don't mind the concurrency issues.

export HISTCONTROL=ignoreboth

Here is what I use..
[vanuganti# ~]$ grep HIST .alias*
.alias:HISTCONTROL="erasedups"
.alias:HISTSIZE=20000
.alias:HISTIGNORE=ls:ll:"ls -altr":"ls -alt":la:l:pwd:exit:mc:su:df:clear:ps:h:history:"ls -al"
.alias:export HISTCONTROL HISTSIZE HISTIGNORE
[vanuganti# ~]$
and working
[vanuganti# ~]$ pwd
/Users/XXX
[vanuganti# ~]$ pwd
/Users/XXX
[vanuganti# ~]$ history | grep pwd | wc -l
1

inside your .bash_profile add
alias hist="history -a && hist.py"
then put this on your path as hist.py and make it executable
#!/usr/bin/env python
from __future__ import print_function
import os, sys
home = os.getenv("HOME")
if not home :
sys.exit(1)
lines = open(os.path.join(home, ".bash_history")).readlines()
history = []
for s in lines[:: -1] :
s = s.rstrip()
if s not in history :
history.append(s)
print('\n'.join(history[:: -1]))
now when you want the short list just type hist

Related

why alias won't change directory with ls -latr? [duplicate]

This question already has answers here:
Make a Bash alias that takes a parameter?
(24 answers)
Closed last month.
I'm very interested in why this works this way and if we find a solution that's just a benefit of asking the question.
Using kshell,bash and observed the same results. Below is from GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu).
Below is from terminal.
alias tryme='tb=$1;cd $tb'
pwd
/home/tbink1
tryme /home/tbink1/Documents
pwd
/home/tbink1/Documents
But using below doesn't switch directories.
alias tryme='tb=$1;cd $tb;ls -latr'
pwd
/home/tbink1/Documents
tryme /home/tbink1/Pictures
<file list from /home/tbink1/Pictures>
pwd
/home/tbink1/Documents
Mystery to me why the second alias isn't changing directories. The second alias is what I would like to get working. Thanks for any help you give.
Alias doesn't take arguments. It is replaced.
$ tryme /home/tbink1/Pictures
# tryme is _replaced_ by the alias, literally:
$ tb=$1;cd $tb;ls -latr /home/tbink1/Pictures
# then it's executed
# $1 is empty
+ tb=
# $tb is empty,
+ cd
# and ls lists the directory
+ ls -latr /home/tbink1/Pictures
cd with no arguments changes to home directory. $1 is your shell $1, i.e. bash -s this_is_first_arg:
$ bash -s this_is_first_arg
$ echo $1
this_is_first_arg
$ alias tryme='tb=$1;cd $tb'
$ tryme
bash: cd: this_is_first_arg: No such file or directory
Use a function, not an alias.

Configure bash_history to show the pwd of each command [duplicate]

I'd like to save the current directory where the each command was issued alongside the command in the history. In order not to mess things up, I was thinking about adding the current directory as a comment at the end of the line. An example might help:
$ cd /usr/local/wherever
$ grep timmy accounts.txt
I'd like bash to save the last command as:
grep timmy accounts.txt # /usr/local/wherever
The idea is that this way I could immediately see where I issued the command.
One-liner version
Here is a one-liner version. It's the original. I've also posted a short function version and a long function version with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. This post has some information on how they all work which may not be duplicated in the others.
Add the following to your ~/.bashrc file:
export PROMPT_COMMAND='hpwd=$(history 1); hpwd="${hpwd# *[0-9]* }"; if [[ ${hpwd%% *} == "cd" ]]; then cwd=$OLDPWD; else cwd=$PWD; fi; hpwd="${hpwd% ### *} ### $cwd"; history -s "$hpwd"'
This makes a history entry that looks like:
rm subdir/file ### /some/dir
I use ### as a comment delimiter to set it apart from comments that the user might type and to reduce the chance of collisions when stripping old path comments that would otherwise accumulate if you press enter on a blank command line. Unfortunately, the side affect is that a command like echo " ### " gets mangled, although that should be fairly rare.
Some people will find the fact that I reuse the same variable name to be unpleasant. Ordinarily I wouldn't, but here I'm trying to minimize the footprint. It's easily changed in any case.
It blindly assumes that you aren't using HISTTIMEFORMAT or modifying the history in some other way. It would be easy to add a date command to the comment in lieu of the HISTTIMEFORMAT feature. However, if you need to use it for some reason, it still works in a subshell since it gets unset automatically:
$ htf="%Y-%m-%d %R " # save it for re-use
$ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
There are a couple of very small problems with it. One is if you use the history command like this, for example:
$ history 3
echo "hello world" ### /home/dennis
ls -l /tmp/file ### /home/dennis
history 3
The result will not show the comment on the history command itself, even though you'll see it if you press up-arrow or issue another history command.
The other is that commands with embedded newlines leave an uncommented copy in the history in addition to the commented copy.
There may be other problems that show up. Let me know if you find any.
How it works
Bash executes a command contained in the PROMPT_COMMAND variable each time the PS1 primary prompt is issued. This little script takes advantage of that to grab the last command in the history, add a comment to it and save it back.
Here it is split apart with comments:
hpwd=$(history 1) # grab the most recent command
hpwd="${hpwd# *[0-9]* }" # strip off the history line number
if [[ ${hpwd%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
cwd=$OLDPWD
else
cwd=$PWD
fi
hpwd="${hpwd% ### *} ### $cwd" # strip off the old ### comment if there was one so they
# don't accumulate, then build the comment
history -s "$hpwd" # replace the most recent command with itself plus the comment
hcmnt - long function version
Here is a long version in the form of a function. It's a monster, but it adds several useful features. I've also posted a one-liner (the original) and a shorter function. I like the function versions because they won't clobber other variables in your environment and
they're much more readable than the one-liner. Read the entry for the one-liner and the commments in the function below for additional information on how it works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnt in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnt
export hcmntextra='date "+%Y%m%d %R"'
export PROMPT_COMMAND='hcmnt'
Don't edit the function's file where PROMPT_COMMAND or hcmntextra are set. Leave them as is so they remain as defaults. Include them in your .bashrc as shown above and edit them there to set options for hcmnt or to change or unset hcmntextra. Unlike the short function, with this one you must both have the hcmntextra variable set and use the -e option to make that feature work.
You can add several options which are documented (with a couple of examples) in the comments in the function. One notable feature is to have the history entry with appended comment logged to a file and leave the actual history untouched. In order to use this function, just
add the -l filename option like so:
export PROMPT_COMMAND="hcmnt -l ~/histlog"
You can use any combination of options, except that -n and -t are mutually exclusive.
#!/bin/bash
hcmnt() {
# adds comments to bash history entries (or logs them)
# by Dennis Williamson - 2009-06-05 - updated 2009-06-19
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
# the comments can include the directory
# that was current when the command was issued
# plus optionally, the date or other information
# set the bash variable PROMPT_COMMAND to the name
# of this function and include these options:
# -e - add the output of an extra command contained in the hcmntextra variable
# -i - add ip address of terminal that you are logged in *from*
# if you're using screen, the screen number is shown
# if you're directly logged in, the tty number or X display number is shown
# -l - log the entry rather than replacing it in the history
# -n - don't add the directory
# -t - add the from and to directories for cd commands
# -y - add the terminal device (tty)
# text or a variable
# Example result for PROMPT_COMMAND='hcmnt -et $LOGNAME'
# when hcmntextra='date "+%Y%m%d %R"'
# cd /usr/bin ### mike 20090605 14:34 /home/mike -> /usr/bin
# Example for PROMPT_COMMAND='hcmnt'
# cd /usr/bin ### /home/mike
# Example for detailed logging:
# when hcmntextra='date "+%Y%m%d %R"'
# and PROMPT_COMMAND='hcmnt -eityl ~/.hcmnt.log $LOGNAME#$HOSTNAME'
# $ tail -1 ~/.hcmnt.log
# cd /var/log ### dave#hammerhead /dev/pts/3 192.168.1.1 20090617 16:12 /etc -> /var/log
# INSTALLATION: source this file in your .bashrc
# will not work if HISTTIMEFORMAT is used - use hcmntextra instead
export HISTTIMEFORMAT=
# HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:
# $ htf="%Y-%m-%d %R " # save it for re-use
# $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
local script=$FUNCNAME
local hcmnt=
local cwd=
local extra=
local text=
local logfile=
local options=":eil:nty"
local option=
OPTIND=1
local usage="Usage: $script [-e] [-i] [-l logfile] [-n|-t] [-y] [text]"
local newline=$'\n' # used in workaround for bash history newline bug
local histline= # used in workaround for bash history newline bug
local ExtraOpt=
local LogOpt=
local NoneOpt=
local ToOpt=
local tty=
local ip=
# *** process options to set flags ***
while getopts $options option
do
case $option in
e ) ExtraOpt=1;; # include hcmntextra
i ) ip="$(who --ips -m)" # include the terminal's ip address
ip=($ip)
ip="${ip[4]}"
if [[ -z $ip ]]
then
ip=$(tty)
fi;;
l ) LogOpt=1 # log the entry
logfile=$OPTARG;;
n ) if [[ $ToOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
NoneOpt=1 # don't include path
fi;;
t ) if [[ $NoneOpt ]]
then
echo "$script: can't include both -n and -t."
echo $usage
return 1
else
ToOpt=1 # cd shows "from -> to"
fi;;
y ) tty=$(tty);;
: ) echo "$script: missing filename: -$OPTARG."
echo $usage
return 1;;
* ) echo "$script: invalid option: -$OPTARG."
echo $usage
return 1;;
esac
done
text=($#) # arguments after the options are saved to add to the comment
text="${text[*]:$OPTIND - 1:${#text[*]}}"
# *** process the history entry ***
hcmnt=$(history 1) # grab the most recent command
# save history line number for workaround for bash history newline bug
histline="${hcmnt% *}"
hcmnt="${hcmnt# *[0-9]* }" # strip off the history line number
if [[ -z $NoneOpt ]] # are we adding the directory?
then
if [[ ${hcmnt%% *} == "cd" ]] # if it's a cd command, we want the old directory
then # so the comment matches other commands "where *were* you when this was done?"
if [[ $ToOpt ]]
then
cwd="$OLDPWD -> $PWD" # show "from -> to" for cd
else
cwd=$OLDPWD # just show "from"
fi
else
cwd=$PWD # it's not a cd, so just show where we are
fi
fi
if [[ $ExtraOpt && $hcmntextra ]] # do we want a little something extra?
then
extra=$(eval "$hcmntextra")
fi
# strip off the old ### comment if there was one so they don't accumulate
# then build the string (if text or extra aren't empty, add them plus a space)
hcmnt="${hcmnt% ### *} ### ${text:+$text }${tty:+$tty }${ip:+$ip }${extra:+$extra }$cwd"
if [[ $LogOpt ]]
then
# save the entry in a logfile
echo "$hcmnt" >> $logfile || echo "$script: file error." ; return 1
else
# workaround for bash history newline bug
if [[ $hcmnt != ${hcmnt/$newline/} ]] # if there a newline in the command
then
history -d $histline # then delete the current command so it's not duplicated
fi
# replace the history entry
history -s "$hcmnt"
fi
} # END FUNCTION hcmnt
# set a default (must use -e option to include it)
export hcmntextra='date "+%Y%m%d %R"' # you must be really careful to get the quoting right
# start using it
export PROMPT_COMMAND='hcmnt'
update 2009-06-19: Added options useful for logging (ip and tty), a workaround for the duplicate entry problem, removed extraneous null assignments
You could install Advanced Shell History, an open source tool that writes your bash or zsh history to a sqlite database. This records things like the current working directory, the command exit code, command start and stop times, session start and stop times, tty, etc.
If you want to query the history database, you can write your own SQL queries, save them and make them available within the bundled ash_query tool. There are a few useful prepackaged queries, but since I know SQL pretty well, I usually just open the database and query interactively when I need to look for something.
One query I find very useful, though, is looking at the history of the current working directory. It helps me remember where I left off when I was working on something.
vagrant#precise32:~$ ash_query -q CWD
session
when what
1
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
And the same history using the current working directory (and anything below it):
vagrant#precise32:~$ ash_query -q RCWD
session
where
when what
1
/home/vagrant/advanced-shell-history
2014-08-27 17:11:34 nano ~/.bashrc
2014-08-27 17:12:54 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:12:57 source /usr/lib/advanced_shell_history/bash
2014-08-27 17:13:05 cd
/home/vagrant
2014-08-27 17:13:07 ls -la
2014-08-27 17:13:09 cd .ash
/home/vagrant/.ash
2014-08-27 17:13:10 ls
2014-08-27 17:13:11 ls -l
2014-08-27 17:13:16 sqlite3 history.db
2014-08-27 17:13:43 ash_query
2014-08-27 17:13:50 ash_query -Q
2014-08-27 17:13:56 ash_query -q DEMO
2014-08-27 17:14:39 ash_query -q ME
2014-08-27 17:16:26 cd
/home/vagrant
2014-08-27 17:16:27 ls
2014-08-27 17:16:33 rm -rf advanced-shell-history/
2014-08-27 17:16:35 ls
2014-08-27 17:16:37 less postinstall.sh
2014-08-27 17:16:57 sudo reboot -n
FWIW - I'm the author and maintainer of the project.
hcmnts - short function version
Here is a short version in the form of a function. I've also posted a one-liner (the original) and a longer function with several added features. I like the function versions because they won't clobber other variables in your environment and they're much more readable than the one-liner. Read the entry for the one-liner for additional information on how this works and some limitations. I've posted each version in its own answer in order to keep things more organized.
To use this one, save it in a file called hcmnts in a location like /usr/local/bin (you can chmod +x it if you want) then source it in your ~/.bashrc like this:
source /usr/local/bin/hcmnts
Comment out the line that sets hcmntextra if you don't want the date and time (or you can change its format or use some other command besides date).
That's all there is to it.
#!/bin/bash
hcmnts() {
# adds comments to bash history entries
# the *S*hort version of hcmnt (which has many more features)
# by Dennis Williamson
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
# INSTALLATION: source this file in your .bashrc
# will not work if HISTTIMEFORMAT is used - use hcmntextra instead
export HISTTIMEFORMAT=
# HISTTIMEFORMAT still works in a subshell, however, since it gets unset automatically:
# $ htf="%Y-%m-%d %R " # save it for re-use
# $ (HISTTIMEFORMAT=$htf; history 20)|grep 11:25
local hcmnt
local cwd
local extra
hcmnt=$(history 1)
hcmnt="${hcmnt# *[0-9]* }"
if [[ ${hcmnt%% *} == "cd" ]]
then
cwd=$OLDPWD
else
cwd=$PWD
fi
extra=$(eval "$hcmntextra")
hcmnt="${hcmnt% ### *}"
hcmnt="$hcmnt ### ${extra:+$extra }$cwd"
history -s "$hcmnt"
}
export hcmntextra='date +"%Y%m%d %R"'
export PROMPT_COMMAND='hcmnts'
For those who want this in zsh I've modified Jeet Sukumaran's implementation and percol to allow interactive keyword searching and extraction of either the command or path it was executed in. It's also possible to filter out duplicate commands and hide fields (date, command, path)
Here's a one liner of what I use. Sticking it here because it's vastly simpler, and I have no problem with per-session history, I just also want to have a history with the working directory.
Also the one-liner above mucks with your user interface too much.
export PROMPT_COMMAND='if [ "$(id -u)" -ne 0 ]; then echo "$(date "+%Y-%m-%d.%H:%M:%S") $(pwd) $(history 1)" >> ~/.bash.log; fi'
Since my home dir is typically a cross-mounted gluster thingy, this has the side effect of being a history of everything I've ever done. Optionally add $(hostname) to the echo command above... depending on your working environment.
Even with 100k entries, grep is more than good enough. No need to sqlite log it. Just don't type passwords on the command line and you're good. Passwords are 90's tech anyway!
Also, for searching I tend to do this:
function hh() {
grep "$1" ~/.bash.log
}
Gentleman this works better.. The only thing I can not figure out is how to make the script NOT log to syslog on login and log the last command in history. But works like a charm so far.
#!/bin/bash
trackerbash() {
# adds comments to bash history entries
# by Dennis Williamson
# http://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history
# (thanks to Lajos Nagy for the idea)
#Supper Enhanced by QXT
# INSTALLATION: source this file in your .bashrc
export HISTTIMEFORMAT=
# export HISTTIMEFORMAT='%F %T '
local hcmnt
local cwd
local extra
local thistty
local whoiam
local sudouser
local shelldate
local TRACKIP
local TRACKHOST
thistty=`/usr/bin/tty|/bin/cut -f3-4 -d/`
whoiam=`/usr/bin/whoami`
sudouser=`last |grep $thistty |head -1 | awk '{ print $1 }' |cut -c 1-10`
hcmnt=$(history 1)
hcmnt="${hcmnt# *[0-9]* }"
cwd=`pwd`
hcmnt="${hcmnt% ### *}"
hcmnt=" $hcmnt ${extra:+$extra }"
shelldate=`date +"%Y %b %d %R:%S"`
TRACKHOST=`whoami | sed -r "s/.*\((.*)\).*/\\1/"`
TRACKIP=`last |grep $thistty |head -1 | awk '{ print $3 }'`
logger -p local1.notice -t bashtracker -i -- "$sudouser ${USER}: $thistty: $TRACKIP: $shelldate: $cwd : $hcmnt"
history -w
}
export PROMPT_COMMAND='trackerbash'
Full disclosure: I'm the author of the FOSS-tool
shournal - A (file-) journal for your shell:
Using it's bash integration, the working directory of a command is also stored within shournal's sqlite-database and can be retrieved via
shournal --query -cmdcwd "$PWD"
Querying for sub-working-directories can be done with
shournal --query -cmdcwd -like "$PWD/%"
You could consider an independent project (I wrote it) that supports saving the path for each command: https://github.com/chrissound/MoscoviumOrange
Where you can add a hook into Bash to save each entry with:
$(jq -n --arg command "$1" --arg path "$PWD" '{"command":$command, "path":$path}' | "$(echo 'readlink -f $(which nc)' | nix run nixpkgs.netcat)" -N -U ~/.config/moscoviumOrange/monitor.soc &)

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
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.
Your ~/.bash_history file should already contain your complete command history. You could use something like
cat ~/.bash_history | grep -v cd | egrep -v 'cd|ls|...'
to filter out the commands you're not interested in.
So for the list you specified:
cat ~/.bash_history | egrep -v 'more|less|cd|open|ls|pwd|nano|man|help'
I completed Mark Reed answer with what i precisely wanted. Here is my code:
# changes the .bash_history file mode to append
shopt -s histappend
#configures the history -a command to be run at each shell prompt. The -a immediately writes the current/new lines to the history file.
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"
#list of command i don't want in my history
HISTIGNORE='ls*:exit:pwd:clear:cd*:man*:more*:less*:head*:tail*:nano*:open*:help*'
#set no limit to the history file size
HISTSIZE= HISTFILESIZE=

Vim shell commands (c flag) behaving differently in bash

If I run this in the terminal (Mac OSX):
vim dump.md -c 'vsplit poa.md' -c 'split one.md' -c ':wincmd h'
It works great (creates three windows with those files).
If I have it as part of a bash script, there's a problem. After doing what it's supposed to do, it leaves me with this in the vim status line:
1:dump.md 2:poa.md 3:one.md
1:dump.md 2:poa.md 3:one.md
Press ENTER or type command to continue
I have to press ENTER 6 times to clear the status line and return to editing (each ENTER outputs the above again).
Anyway around this?
Also, not sure if this is significant, but vim is aliased to mvim (MacVim).
EDIT
Here is the bash script, although I don't think it matters I've run the whole script separately before manually putting the vim dump.md... command it, and it works fine.
13
12 #!/bin/bash
11
10 cd ~/Dropbox/Journal/dumps/
9
8 LAST=`ls -tAF | grep '/$' | head -1`
7 NEW=dump-$(date +"%Y-%m-%d_%T")
6
5 mkdir $NEW
4 cd $NEW
3
2 cp ../$LAST/poa.md ./poa.md
1
14 vim dump.md -c 'vsplit poa.md' -c 'split one.md' -c ':wincmd h'
1
At first:
ls -al
And see just your file is existed...If your file is test make sure vim doesn't cread such files:
.test OR test~ OR something like these
Then :
vim file
Do your changes...
After that close it by saying:
:wq!
Then try to open it again...The problem should be solved
UPDATE
try this one:
ls -a | grep swp
if there was a file like : .script.swp or something like these you should remove them...
Your problem would be solved...You should see if your script it existed with .script.... and you should remove it...
If you can't find files start with . try to move all files(scripts) to another directory then work with them..and use :q! to quite and use :wq! to save and quite...

How to find out where alias (in the bash sense) is defined when running Terminal in Mac OS X

How can I find out where an alias is defined on my system? I am referring to the kind of alias that is used within a Terminal session launched from Mac OS X (10.6.3).
For example, if I enter the alias command with no parameters at a Terminal command prompt, I get a list of aliases that I have set, for example:
alias mysql='/usr/local/mysql/bin/mysql'
However, I have searched all over my system using Spotlight and mdfind in various startup files and so far can not find where this alias has been defined. ( I did it a long time ago and didn't write down where I assigned the alias).
For OSX, this 2-step sequence worked well for me, in locating an alias I'd created long ago and couldn't locate in expected place (~/.zshrc).
cweekly:~ $ which la
la: aliased to ls -lAh
cweekly:~$ grep -r ' ls -lAh' ~
/Users/cweekly//.oh-my-zsh/lib/aliases.zsh:alias la='ls -lAh'
Aha! "Hiding" in ~/.oh-my-zsh/lib/aliases.zsh. I had poked around a bit in .oh-my-zsh but had overlooked lib/aliases.zsh.
you can just simply type in alias on the command prompt to see what aliases you have. Otherwise, you can do a find on the most common places where aliases are defined, eg
grep -RHi "alias" /etc /root
First use the following commands
List all functions
functions
List all aliases
alias
If you aren't finding the alias or function consider a more aggressive searching method
Bash version
bash -ixlc : 2>&1 | grep thingToSearchHere
Zsh version
zsh -ixc : 2>&1 | grep thingToSearchHere
Brief Explanation of Options
-i Force shell to be interactive.
-c Take the first argument as a command to execute
-x -- equivalent to --xtrace
-l Make bash act as if invoked as a login shell
Also in future these are the standard bash config files
/etc/profile
~/.bash_profile or ~/.bash_login or ~/.profile
~/.bash_logout
~/.bashrc
More info: http://www.heimhardt.com/htdocs/bashrcs.html
A bit late to the party, but I was having the same problem (trying to find where the "l." command was aliased in RHEL6), and ended up in a place not mentioned in the previous answers. It may not be found in all bash implementations, but if the /etc/profile.d/ directory exists, try grepping there for unexplained aliases. That's where I found:
[user#server ~]$ grep l\\. /etc/profile.d/*
/etc/profile.d/colorls.csh:alias l. 'ls -d .*'
/etc/profile.d/colorls.csh:alias l. 'ls -d .* --color=auto'
/etc/profile.d/colorls.sh: alias l.='ls -d .*' 2>/dev/null
/etc/profile.d/colorls.sh:alias l.='ls -d .* --color=auto' 2>/dev/null
The directory isn't mentioned in the bash manpage, and isn't properly part of where bash searches for profile/startup info, but in the case of RHEL you can see the calling code within /etc/profile:
for i in /etc/profile.d/*.sh ; do
if [ -r "$i" ]; then
if [ "${-#*i}" != "$-" ]; then
. "$i"
else
. "$i" >/dev/null 2>&1
fi
fi
done
Please do check custom installations/addons/plugins you have added, in addition to the .zshrc/.bashrc/.profile etc files
So for me: it was git aliased to 'g'.
$ which g
g: aliased to git
Then I ran the following command to list all aliases
$ alias
I found a whole lot of git related aliases that I knew I had not manually added.
This got me thinking about packages or configurations I had installed. And so went to the
.oh-my-zsh
directory. Here I ran the following command:
$ grep -r 'git' . |grep -i alias
And lo and behold, I found my alias in :
./plugins/git/git.plugin.zsh
I found the answer ( I had been staring at the correct file but missed the obvious ).
The aliases in my case are defined in the file ~/.bash_profile
Somehow this eluded me.
For more complex setups (e.g. when you're using a shell script framework like bash-it, oh-my-zsh or the likes) it's often useful to add 'alias mysql' at key positions in your scripts. This will help you figure out exactly when the alias is added.
e.g.:
echo "before sourcing .bash-it:"
alias mysql
. $HOME/.bash-it/bash-it.sh
echo "after sourcing bash:"
alias mysql
I think that maybe this is similar to what ghostdog74 meant however their command didn't work for me.
I would try something like this:
for i in `find . -type f`; do # find all files in/under current dir
echo "========"
echo $i # print file name
cat $i | grep "alias" # find if it has alias and if it does print the line containing it
done
If you wanted to be really fancy you could even add an if [[ grep -c "alias" ]] then <print file name>
The only reliable way of finding where the alias could have been defined is by analyzing the list of files opened by bash using dtruss.
If
$ csrutil status
System Integrity Protection status: enabled.
you won't be able to open bash and you may need a copy.
$ cp /bin/bash mybash
$ $ codesign --remove-signature mybash
and then use
sudo dtruss -t open ./mybash -ic exit 2>&1 | awk -F'"' '/^open/ {print substr($2, 0, length($2)-2)}'
to list all the files where the alias could have been defined, like
/dev/dtracehelper
/dev/tty
/usr/share/locale/en_CA.UTF-8/LC_MESSAGES/BASH.mo
/usr/share/locale/en_CA.utf8/LC_MESSAGES/BASH.mo
/usr/share/locale/en_CA/LC_MESSAGES/BASH.mo
/usr/share/locale/en.UTF-8/LC_MESSAGES/BASH.mo
/usr/share/locale/en.utf8/LC_MESSAGES/BASH.mo
/usr/share/locale/en/LC_MESSAGES/BASH.mo
/Users/user/.bashrc
/Users/user/.bash_aliases
/Users/user/.bash_history
...
Try: alias | grep name_of_alias
Ex.: alias | grep mysql
or, as already mentioned above
which name_of_alias
In my case, I use Oh My Zsh, so I put aliases definition in ~/.zshrc file.

Resources