Bash one liner - Test if a file exists and source if it does other exit with error
10,719
Solution 1
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; }
Solution 2
[[ -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.
Author by
skanga
Updated on July 03, 2022Comments
-
skanga almost 2 years
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
-
konsolebox almost 10 yearsThis would also run the message if
source "${MY_HOME}/setup-env.sh"
ends with nonzero status code. -
anubhava almost 10 yearsYes that's good point, I think that is pitfall of doing this all in one line. Obviously
source "${MY_HOME}/setup-env.sh"
cannot be done in a sub shell.