开发者

Include additional files in .bashrc

开发者 https://www.devze.com 2023-02-09 20:35 出处:网络
I have some开发者_JAVA百科 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?Add source /whatever/file (or . /wha

I have some开发者_JAVA百科 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?


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消