如何将多个文件添加到我的 .bashrc 中?

如何将多个文件添加到我的 .bashrc 中?

我想将每个 Bash 函数编写在一个单独的文件中,以便于版本控制,并将所有这些函数都放在我的.bashrc.

有没有比例如更强大的方法:

. ~/.bash_functions/*.sh

答案1

只需用适当的错误检查来包围它:

fn_dir=~/.bash_functions
if [ -d "$fn_dir" ]; then
    for file in "$fn_dir"/*; do
        [ -r "$file" ] && . "$file"
    done
fi

答案2

至于一次源多个文件,可以通过创建其串联输出的重定向来完成,例如:

source <(cat ~/.bash_functions/*.sh)

至于稳健的部分,您可能需要为您采购的任何内容正确设置错误检查,例如:

source <(cat ~/.bash_functions/*.sh)||echo "ERROR: failed while sourcing $?";exit 1

这是另一个片段,您还可以在其中验证源文件本身,如下所示:

sourced_files=$(source <(cat ~/.bash_functions/*.sh) 2>&1 > /dev/null)
if [ -n "$sourced_files" ]; then
 echo "ERROR: nonzero returned"
fi

如果可能的话,在您采购的任何内容中添加错误验证,并使用自定义错误代码,那就更好了,这样您就可以更好地跟踪失败的位置,例如:

err=0
...
...
# your shell script
...
some-command-i-wanna-check
if [ "$?" -ne 0 ];then
 echo "ERROR: my failed description"
 err=101
 exit $err 
fi

相关内容