[英]What is the most concise way to source a file (only if it exists) in Bash?
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
Is defining your own version of @include
an option?定义您自己的@include
版本是一个选项吗?
include () {
[[ -f "$1" ]] && source "$1"
}
include FILE
如果您担心不重复文件名的单行,也许:
FILE=/path/to/some/file && test -f $FILE && source $FILE
如果您担心警告(并且不存在源文件对您的脚本来说并不重要),只需摆脱警告:
source FILE 2> /dev/null
You could try你可以试试
test -f $FILE && source $FILE
If test
returns false, the second part of &&
is not evaluated如果test
返回 false,则不会评估&&
的第二部分
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
If you want to always get a clean exit code, and continue no matter what, then you can do:如果您想始终获得一个干净的退出代码,并且无论如何都要继续,那么您可以执行以下操作:
source ~/.bashrc || true && echo 'is always executed!'
And if you also want to get rid of the error message then:如果您还想摆脱错误消息,则:
source ~/.bashrc 2> /dev/null || true && echo 'is always executed!'
如果您不关心脚本的输出,您可以使用以下内容将标准错误重定向到/dev/null
:
$ source FILE 2> /dev/null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.