Skip to content

Instantly share code, notes, and snippets.

@hflamboauto1
Forked from magnetikonline/README.md
Created July 6, 2016 11:02
Show Gist options
  • Save hflamboauto1/594e9361feff23c1e7d890a3a5c1cc02 to your computer and use it in GitHub Desktop.
Save hflamboauto1/594e9361feff23c1e7d890a3a5c1cc02 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

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
# will return zero (which is true)
if functionTwo "value"; then
	echo "evaluates true"
else
	echo "evaluates false"
fi

# will return 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