Include additional files in .bashrc

LinuxShellCommand LineBash

Linux Problem Overview


I have some stuff I want to perform in .bashrc which I would prefer to exist in another file on the system. How can I include this file into .bashrc?

Linux Solutions


Solution 1 - Linux

Add source /whatever/file (or . /whatever/file) into .bashrc where you want the other file included.

Solution 2 - Linux

To prevent errors you need to first check to make sure the file exists. Then source the file. Do something like this.

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

Solution 3 - Linux

Here is a one liner!

[ -f $HOME/.bashrc_aliases ] && . $HOME/.bashrc_aliases

Fun fact: shell (and most other languages) are lazy. If there are a series of conditions joined by a conjunction (aka "and" aka &&) then evaluation will begin from the left to the right. The moment one of the conditions is false, the rest of the expressions won't be evaluated, effectively "short circuiting" other expressions.

Thus, you can put a command you want to execute on the right of a conditional, it won't execute unless every condition on the left is evaluated as "true."

Solution 4 - Linux

If you have multiple files you want to load that may or may not exist, you can keep it somewhat elegant by using a for loop.

files=(somefile1 somefile2)
path="$HOME/path/to/dir/containing/files/"
for file in ${files[@]}
do 
    file_to_load=$path$file
    if [ -f "$file_to_load" ];
    then
        . $file_to_load
        echo "loaded $file_to_load"
    fi
done

The output would look like:

$ . ~/.bashrc
loaded $HOME/path/to/dir/containing/files/somefile1
loaded $HOME/path/to/dir/containing/files/somefile2

Solution 5 - Linux

I prefer to check version first and assign variable for path config:

if [ -n "${BASH_VERSION}" ]; then
  filepath="${HOME}/ls_colors/monokai.sh"
  if [ -f "$filepath" ]; then
    source "$filepath"
  fi
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFragsworthView Question on Stackoverflow
Solution 1 - LinuxJeremiah WillcockView Answer on Stackoverflow
Solution 2 - LinuxNickView Answer on Stackoverflow
Solution 3 - LinuxAndrew AllbrightView Answer on Stackoverflow
Solution 4 - Linuxmodle13View Answer on Stackoverflow
Solution 5 - LinuxNick TsaiView Answer on Stackoverflow