如果 Bash 中存在包含/源脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10735574/
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-09-18 02:22:10  来源:igfitidea点击:

Include/Source script if it exists in Bash

basherror-handlinginclude

提问by Bart van Heukelom

In Bash scripting, is there a single statement alternative for this?

在 Bash 脚本中,是否有一个单独的语句替代?

if [ -f /path/to/some/file ]; then
    source /path/to/some/file
fi

The most important thing is that the filename is there only once, without making it a variable (which adds even more lines).

最重要的是文件名只出现一次,没有使它成为变量(这会增加更多行)。

For example, in PHP you could do it like this

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

@include("/path/to/some/file"); // @ makes it ignore errors

回答by chepner

Is defining your own version of @includean option?

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

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

include FILE

回答by Bryan Oakley

If you're concerned about a one-liner without repeating the filename, perhaps:

如果您担心不重复文件名的单行,也许:

FILE=/path/to/some/file && test -f $FILE && source $FILE

回答by mzet

If you are concerned about warning (and lack of existence of sourced file isn't critical for your script) just get rid of the warning:

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

source FILE 2> /dev/null

回答by Attila

You could try

你可以试试

test -f $FILE && source $FILE

If testreturns false, the second part of &&is not evaluated

如果test返回 false,&&则不评估第二部分

回答by Jakob

This is the shortest I could get (filename plus 20 characters):

这是我能得到的最短的(文件名加 20 个字符):

F=/path/to/some/file;[ -f $F ] && . $F

It's equivalent to:

它相当于:

F=/path/to/some/file 
test -f $F && source $F

To improve readability, I prefer this form:

为了提高可读性,我更喜欢这种形式:

FILE=/path/to/some/file ; [ -f $FILE ] && . $FILE

回答by ayaz

If you are not concerned with the output of the script, you could just redirect standard error to /dev/nullwith something like this:

如果您不关心脚本的输出,您可以将标准错误重定向到/dev/null以下内容:

$ source FILE 2> /dev/null

$ source FILE 2> /dev/null