Explaining the contents of the ~/.profile file

Solution 1:

Simplified version:

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

This parts checks wheter ~/.profile itself is being sourced by a Bash instance, and if that's the case sources in turn ~/.bashrc; this is a way to include the user's settings stored in ~/.bashrc e.g. also in login shells, which normally don't source ~/.bashrc;

if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

This part checks whether ~/bin exists, and if that's the case prepends ~/bin to the current value of $PATH; this is done so that potential executables / scripts present in ~/bin take precedence over executables / scripts present in other paths included in $PATH (e.g. by placing an executable named cat in ~/bin, when running cat that executable would be run in place of the usual /bin/cat).


Detailed version:

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

This part checks whether the expansion of $BASH_VERSION has a non-zero lenght (if [ -n "$BASH_VERSION" ]), and if that's the case, if the expansion of $HOME/.bashrc exists and is a regular file (if [ -f "$HOME/.bashrc" ]), the expansion of $HOME/.bashrc is sourced.

Since Bash sets $BASH_VERSION upon invocation, checking whether $BASH_VERSION has a non-zero lenght is a robust way of determining whether the file itself is being sourced by a Bash instance.

This is why when invoking Bash as a login shell on Ubuntu the user's settings stored in ~/.bashrc are included (this is not necessarily the case for other distributions); Bash itself only sources ~/.profile when invoked as a login shell, and this is a way to go around that;

if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

This part checks whether the expansion of $HOME/bin exists and is a directory (if [ -d "$HOME/bin" ]), and if that's the case prepends the expansion of $HOME/bin to the current value of $PATH (PATH="$HOME/bin:$PATH"; $HOME is normally set to the user's home directory).

This is done so that potential executables / scripts present in the expansion of $HOME/bin take precedence over executables / scripts present in other paths included in $PATH.