Old Guy New Trick

An old guys journey to learn how to code.

Keep this cat in the bag


Author: John on December 01, 2015

Today I'd like to talk about a handy command line tool that I find myself using frequently.  Especially since I seem to be learning a lot of new things, and my memory recall needs improvement.  The commands we will look at are cat and grep.   These can be handy for searching on recently used commands by viewing the .zsh_history / .bash_history files.

➜  ~  cat ~/.zsh_history | grep 'git checkout'
: 1415665986:0;git checkout spec/features/playground_for_features_spec.rb
...
: 1448367043:0;git checkout master
: 1448386073:0;git checkout bobots
: 1448392731:0;git checkout master
: 1448393378:0;cat .zsh_history | grep 'git checkout -b '
: 1448393438:0;git checkout -b local_branch_name_here --track origin/remote_branch_name_here

In the above example, I was trying remember what git command I needed to use to track and checkout a remote branch that another team member was working on.  

However, one must be careful with your command line tools.  For example, review the results of the following command:

➜  ~  cat ~/.zsh_history| grep export
...
: 1446929055:0;export DB_PROD='REAL_DB_NAME_HERE'
: 1446929063:0;export DB_USERNAME='PROD_USER_ACCOUNT'
: 1446929073:0;export DB_PASSWORD='PROD_USER_PW'
: 1446929086:0;export RAILS_ENV=production
: 1448972169:0;cat ~/.zsh_history| grep export
➜  ~

To prevent those from showing up, use a space before the command. Let's look at an example.  First, we will capture our existing history for the export command:

➜  ~  cat ~/.zsh_history | grep 'export'
[ -z "$TMUX" ] && export TERM=xterm-256color\
: 1444005250:0;export GRB_LICENSE_FILE="/Users/jfhogarty/gurobi.lic"
: 1448974080:0;cat ~/.zsh_history | grep 'export'
➜  ~

Next we will run two new export commands - one without a leading space and one with the space.  Then we will look at our history file again.

➜  ~
➜  ~  export DB_USER_NAME="prod_db_user"
➜  ~   export DB_USER_PW="mySuper$ecr3tPW"
➜  ~

Now let's use our cat and grep combo:

➜  ~  cat ~/.zsh_history | grep 'export'
[ -z "$TMUX" ] && export TERM=xterm-256color\
: 1444005250:0;export GRB_LICENSE_FILE="/Users/jfhogarty/gurobi.lic"
: 1448974080:0;cat ~/.zsh_history | grep 'export'
: 1448975023:0;cat ~/.zsh_history | grep 'export'
: 1448975055:0;export DB_USER_NAME="prod_db_user"
: 1448975145:0;cat ~/.zsh_history | grep 'export'
➜  ~

Pretty neat!

Learn Something New Everyday

Last Edited by: John on December 06, 2015