Linux 在 .bashrc 中包含其他文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4952177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 02:46:58  来源:igfitidea点击:

Include additional files in .bashrc

linuxshellcommand-linebash

提问by Fragsworth

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?

我有一些我想在 .bashrc 中执行的东西,我希望它存在于系统上的另一个文件中。如何将此文件包含到 .bashrc 中?

采纳答案by Jeremiah Willcock

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

source /whatever/file(或. /whatever/file)添加到.bashrc您希望包含其他文件的位置。

回答by Nick

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

回答by modle13

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.

如果您有多个要加载的文件,这些文件可能存在也可能不存在,您可以使用 for 循环使其保持优雅。

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

回答by Nick Tsai

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

回答by Andrew Allbright

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.

有趣的事实:shell(和大多数其他语言)是懒惰的。如果有一系列由连词(又名“和”又名&&)连接的条件,则评估将从左到右开始。当其中一个条件为假时,其余的表达式将不会被评估,从而有效地“短路”了其他表达式。

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

因此,您可以将要执行的命令放在条件的右侧,除非左侧的每个条件都被评估为“真”,否则它不会执行。