包含/源脚本(如果它存在于Bash中)

Bar*_*lom 26 error-handling bash include

在Bash脚本编写中,是否有一个单独的声明替代?

if [ -f /path/to/some/file ]; then
    source /path/to/some/file
fi
Run Code Online (Sandbox Code Playgroud)

最重要的是文件名只有一次,而不是变量(这会增加更多的行).

例如,在PHP中你可以这样做

@include("/path/to/some/file"); // @ makes it ignore errors
Run Code Online (Sandbox Code Playgroud)

che*_*ner 36

是否定义了您自己@include的选项版本?

include () {
    [[ -f "$1" ]] && source "$1"
}

include FILE
Run Code Online (Sandbox Code Playgroud)


Bry*_*ley 16

如果您担心单行而不重复文件名,可能:

FILE=/path/to/some/file && test -f $FILE && source $FILE
Run Code Online (Sandbox Code Playgroud)


小智 10

如果您担心警告(并且源文件不存在对您的脚本不重要),请删除警告:

source FILE 2> /dev/null
Run Code Online (Sandbox Code Playgroud)


Att*_*ila 5

你可以尝试

test -f $FILE && source $FILE
Run Code Online (Sandbox Code Playgroud)

如果返回 false,则不计算test第二部分&&


ccp*_*zza 5

如果您想始终获得干净的退出代码,并无论如何继续,那么您可以这样做:

source ~/.bashrc || true && echo 'is always executed!'
Run Code Online (Sandbox Code Playgroud)

如果您还想摆脱错误消息,那么:

source ~/.bashrc 2> /dev/null || true && echo 'is always executed!'
Run Code Online (Sandbox Code Playgroud)