Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active September 12, 2023 05:06
Show Gist options
  • Save magnetikonline/8a0c64931cfe72af8778 to your computer and use it in GitHub Desktop.
Save magnetikonline/8a0c64931cfe72af8778 to your computer and use it in GitHub Desktop.
Bash if conditions with functions().

Bash if conditions with functions()

Some examples of calling bash functions in if; then; fi conditionals - both functions that echo and return.

#!/bin/bash -e

function functionOne {
	echo -n "$1 - $2"
}

function functionTwo {
	if [[ -n $1 ]]; then
		# a value was given
		return 0 # true
	else
		return 1 # false
	fi
}


# showing what functionOne() will echo back
functionOne "joe mike" "blogs"
echo
functionOne "mike" "smith"
echo
echo

# calling functionOne with parameters (including spaces) and checking result (with spaces too)
if [[ $(functionOne "joe mike" "blogs") == "joe mike - blogs" ]]; then
	echo "functionOne match"
fi

# calling functionTwo() and evaluating it's [return] value
# this returns zero (which is true)
if functionTwo "value"; then
	echo "evaluates true"
else
	echo "evaluates false"
fi

# this returns non-zero (which is false)
if functionTwo ""; then
	echo "evaluates true"
else
	echo "evaluates false"
fi

Output

$ ./example.sh
joe mike - blogs
mike - smith

functionOne() match
evaluates true
evaluates false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment