简体   繁体   English

在 Bash 中获取文件(仅当它存在时)的最简洁方法是什么?

[英]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.

相关问题 Bash:将一串空格读为两个变量的最简洁方法 - Bash: most concise way to read a string of space into two variables 使用Bash编写JSON文件的最有效方法是什么? - What is the most efficient way of writing a JSON file with Bash? 在bash中的文件中进行几种替换的最紧凑或最有效的方法是什么 - What is the most compact or efficient way of doing several subsitutions in a file in bash 最快/最简洁的bash one-liner,用于从文件中提取指定的行 - Quickest/most concise bash one-liner for extracting specified lines from a file 仅当来自 url 的文件存在并隐藏 output 时,来自 url 的源 bash - Source bash from url only if file from the url exists and hide output 在 Bash 中用另一个文件内容替换文件内容的最有效(就速度和行数而言)方法是什么? - What is the most efficient (in terms of speed and number of lines) way to replace a file content by another file content in Bash? 获取自定义 bash 脚本的可接受方式是什么? - What is the acceptable way to source custom bash scripts? 在bash脚本中测试多个值的最有效方法是什么 - What is the most efficient way to test multiple values in a bash script 在bash中移动多个通配符的最有效方法是什么? - What's the most efficient way to move multiple wildcards in bash? 从 Bash 中的 $PATH 变量中删除路径的最优雅方法是什么? - What is the most elegant way to remove a path from the $PATH variable in Bash?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM