Bash脚本中,是否有一种单语句的替代方法?
if [ -f /path/to/some/file ]; then
source /path/to/some/file
fi
最重要的是文件名只出现一次,不要将其作为变量(这会增加更多的代码行)。
例如,在PHP中,您可以这样做
@include("/path/to/some/file"); // @ makes it ignore errors
Bash脚本中,是否有一种单语句的替代方法?
if [ -f /path/to/some/file ]; then
source /path/to/some/file
fi
最重要的是文件名只出现一次,不要将其作为变量(这会增加更多的代码行)。
例如,在PHP中,您可以这样做
@include("/path/to/some/file"); // @ makes it ignore errors
自定义 @include
版本是一种选择吗?
include () {
[[ -f "$1" ]] && source "$1"
}
include FILE
include FILE a b c
和 source FILE a b c
是等价的吗? - chepnersource "$1" "$@"
。至于为什么我没有使用 "$@"
,那只是因为在原始问题中它并不是必需的。 - chepner如果你关心一个不重复文件名的一行代码,可以考虑这样:
FILE=/path/to/some/file && test -f $FILE && source $FILE
set -ex
超出您的控制(例如在构建环境中),那么这就是您想要的答案。 - vcardillo如果您关心警告(且源文件不存在对于您的脚本并不是关键),只需消除该警告:
source FILE 2> /dev/null
test -f $FILE && source $FILE
test
返回false,则不会评估&&
的第二部分。F=/path/to/some/file;[ -f $F ] && . $F
这相当于:
F=/path/to/some/file
test -f $F && source $F
FILE=/path/to/some/file ; [ -f $FILE ] && . $FILE
如果您希望始终获得干净的退出代码,并且不管发生什么情况都能够继续运行,则可以执行以下操作:
source ~/.bashrc || true && echo 'is always executed!'
如果你还想消除错误信息,那么:
source ~/.bashrc 2> /dev/null || true && echo 'is always executed!'
如果您不关心脚本的输出,您可以使用以下命令将标准错误重定向到/dev/null
:
$ source FILE 2> /dev/null
我可以发帖,但由于声望不够,不能评论,因此这是对那里面答案的扩展。如果我能评论,我就不会发布看起来像重复回答的内容。在开始挑剔和抱怨它是重复内容之前,请重新阅读我刚才说的话。
include () { test -f "$1" && . "$@"; }