Bash one liner - 测试一个文件是否存在,如果它执行其他错误退出并提供源

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

Bash one liner - Test if a file exists and source if it does other exit with error

phpbashtesting

提问by skanga

In other words I want to make this into a one-liner:

换句话说,我想把它变成一个单行:

    test -e ${MY_HOME}/setup-env.sh || { echo "ERROR: MY_HOME not defined or does not contain srtup-env.sh" 1>&2 ; exit 1; }

    . ${MY_HOME}/setup-env.sh

回答by anubhava

You can use this one liner:

您可以使用这种衬垫:

[[ -e "${MY_HOME}/setup-env.sh" ]] && source "${MY_HOME}/setup-env.sh" || { echo "ERROR: MY_HOME not defined or does not contain srtup-env.sh" 1>&2 ; exit 1; }

回答by konsolebox

[[ -e ${MY_HOME}/setup-env.sh ]] && { source "${MY_HOME}/setup-env.sh"; exit; }; echo "ERROR: MY_HOME not defined or does not contain setup-env.sh" >&2; exit 1

Or if non-bash:

或者如果非 bash:

test -e "${MY_HOME}/setup-env.sh" && { . "${MY_HOME}/setup-env.sh"; exit; }; echo "ERROR: MY_HOME not defined or does not contain setup-env.sh" >&2; exit 1

It's actually not a "one-liner" for me but just a condensed form.

对我来说,它实际上不是“单行”,而只是一种浓缩形式。