Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Created October 14, 2021 05:32
Show Gist options
  • Select an option

  • Save DavidWells/6be87ac216e859ebcac73588bdb48b99 to your computer and use it in GitHub Desktop.

Select an option

Save DavidWells/6be87ac216e859ebcac73588bdb48b99 to your computer and use it in GitHub Desktop.
Conditional variables in bash
# https://stackoverflow.com/questions/2440947/how-to-build-a-conditional-assignment-in-bash
(condition) \
&& variable=true \
|| variable=false
e.g as in
[[ $variableToCheck == "$othervariable, string or number to match" ]] \
&& variable="$valueIfTrue" \
|| variable="$valueIfFalse"
or to get 1 in a positive check, and 0 upon failure (like in the question's example):
[[ $variableToCheck == "$othervariable, string or number to match" ]] \
&& variable=1 \
|| variable=0
(for the last example, - as already mentioned in the notes above - the same can be achieved with boolean negation using a leading exclamation mark:
[[ ! $variableToCheck == "$othervariable, string or number to match" ]]
variable=$?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment