Home » Php » php – Bash one liner – Test if a file exists and source if it does other exit with error

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

Posted by: admin July 12, 2020 Leave a comment

Questions:

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
How to&Answers:

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; }

Answer:

[[ -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:

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.