Bash profile tips and tricks

Check out this XKCD comic and think about what repetitive tasks you could shave seconds off of throughout your day.

Comic showing time savings by task

Props go out to Josh Wyatt for showing me the world of .bash_profile time-saving techniques.

The first thing to do is make it convenient to add new shortcuts to your bash profile.

Do this by adding the following couple of lines.

alias prof="subl ~/.bash_profile"
alias reprof=". ~/.bash_profile"

The first time you add that to your ~/.bash_profile, you'll have to run the command . ~/.bash_profile to reload your profile. Then you can open your profile by running prof and reload it by running reprof when you are done adding your shortcuts.

Let's look at the number of keystrokes it takes to add an alias now:

  • 4: prof
  • 9: alias sc= (5 for 'alias', 1 for the space, 2 for the alias name, 1 for the equal sign
  • n: echo "Whatever command you have to type"
  • 2: command-w, command-q to write and quit the sublime editor window
  • 6: reprof

The total overhead is just 21 characters. If you shorten a 15 character command to 2, you've paid for the investment by the time you've typed the alias twice.

This should become second nature to you.

Think about how often you run the commands:

  • mkdir directory_name
  • cd directory_name

Imagine if you could just do:

  • mcd directory_name

And now you can!

mcd() { mkdir $1 && cd $1; }

Put that in your .bash_profile and with mcd directory_name you can create and cd into a directory all in the same command.

Here are some common git aliases you can use to shave seconds off of your git workflow.

# git alias
alias gs="git status"
alias gc="git commit -a"
alias go="git checkout"
alias gcl="git clone $1"
alias gl="git log --oneline"
alias gp="git push"
alias gb="git branch"
alias grc="git rebase --continue"
alias gpr="git pull --rebase upstream master"
alias glg="git log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short"

If you are using a rebase workflow where you type these commands often:

  • git pull --rebase upstream master
  • git push origin branch/name

You can combine them with a function like so:

function grp() {
	branch_name="$(git symbolic-ref HEAD 2>/dev/null)" ||
	branch_name="(unnamed branch)"
	branch_name=${branch_name##refs/heads/}
	alias gfp="git pull --rebase upstream master && git push origin $branch_name"
}

If you do a lot of work on virtual servers and want to carry your handy bash shortcuts around with you, upload them to GitHub.

Then with a simple

wget https://raw.githubusercontent.com/eihli/dotfiles/master/.bash_profile -O tmp; . tmp; rm tmp;

you have all of your shortcuts. (Or use a URL shortener so you don't have to type out that whole thing.)