在.bashrc 中包含其他文件

我有些东西想表演。我希望它存在于系统的另一个文件中。如何将此文件包含到。巴希尔?

71727 次浏览

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

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

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

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

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."