My Bash Cheatsheet

Here is a selection of my reminders for using the bash shell. I run on Windows, so some of this is Windows-focussed.

Running commands on startup of the bash shell

Two common files that get run on startup of a bash shell are .bash_profile and .bashrc. Depending on how the shell is being opened, one, other, or both of these are run. Here is an excerpt from the bash documentation describing the rules (thanks to nalla for pointing this out):

When Bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bashprofile, ~/.bashlogin, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.

and

When an interactive shell that is not a login shell is started, Bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force Bash to read and execute commands from file instead of ~/.bashrc.

On Windows, a user-specific file .bashrc should be present (or created) in %HOMEPATH%. On Linux, it's ~/.bashrc. You can also create a .bash_profile with the following, which will call the rc file if it's present:

#!/bin/bash

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

In .bashrc you can add aliases for common commands, as well as doing any other kind of setup (like . Here is an example .bashrc file:

#!/bin/bash

# Define some alias for common actions
alias s='git status'  
alias l='git log'  
alias ll='git log --oneline --decorate --graph'  

Chaining commands (from this answer):

A; B = Run A and then B, regardless of success of A
A && B = Run B if A succeeded
A || B = Run B if A failed
A & = Run A in background.

Push'in and Pop'in directories

  • pushd <dir> - cd to a directory and add it to the stack.
  • popd - take the last directory off the stack and cd to it.
  • dirs - list the stack, 'last first'.