How to use a Bash function in an if statement

Used to proper programming languages, it took me a bit to get this straight. Since Bash functions can only return numeric values, you have to use them like this:

function foo {
	if [ (your conditions) ]; then
		return 0
	else
		return 1
	fi
}

foo
if [ "$?" -eq 0 ]; then
	echo "Conditions verified"
else
	echo "Conditions NOT verified"
fi

What’s happening here? You use the function return value ($?) as an argument for the if statement. If you want to work directly with something returned by the function or with strings, you are out of luck (strings are usually addressed using global variables).

But it turns out, you can execute the function using the $() formula, so if you want to return a string (or a number that you can use in the if statement without using $?) you actually have to echo it in the function, like this:

function cpuname {
	echo $(grep 'model name' /proc/cpuinfo | cut -d: -f2 | tail -n1)
}

if [ "x$(cpuname)" == "xAMD Athlon" ]; then
	echo "We are running on AMD";
else
	echo "We are NOT running on AMD";
fi

Why the “x” in the string comparison? Because Bash is broken and in some versions could fail this test with empty strings.

Another example, with numbers:

function usercount {
	echo $(wc -l /etc/passwd | cut -d' ' -f1)
}

if [ "$(usercount)" -gt 100 ]; then
	echo "This system is quite popular"
else
	echo "Ok, it's only the two of us and a few system accounts"
fi

Remember to comment your code, so the people not knowing this particular construct will be able to catch up!

Advertisements

2 thoughts on “How to use a Bash function in an if statement

  1. hi, just a note- if you are using return as just a bool in an if statement, the if can be simplified from :

    foo
    if [ “$?” -eq 0 ]; then

    to simply:

    if foo; then

    If you want an actual value you use echo and command substitution as you did

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s