I'm very new to bash scripting and Linux in general. I'm running Ubuntu Server 10.04 and trying to write a bash script to launch a program. In doing so, I've come across a couple of things that I obviously don't understand. Here is a short script that exemplifies those things:
#!/bin/bash
testfunc() {
echo "Inside function testfunc()"
return 0
}
if [ testfunc ]; then
echo "testfunc() returned true"
else
echo "testfunc() returned false"
fi
exit 0
The output of this script is:
testfunc() returned true
My questions:
Why does the 'echo "some text"' within the function not produce any output? (Actually, I can't even tell if the function is being called.)
Why does the function appear to return a true value?
Like I said, there are obviously some things I don't understand.
You never do call the function. Your if statement is testing a literal string "testfunc", which would always be "true" (as a non empty string)
Correct would be:
#!/bin/bash
testfunc() {
echo "Inside function testfunc()"
return 0
}
if testfunc; then
echo "testfunc() returned true"
else
echo "testfunc() returned false"
fi
Or:
#!/bin/bash
testfunc() {
echo "Inside function testfunc()"
return 0
}
testfunc
if [ $? -eq 0 ]; then
echo "testfunc() returned true"
else
echo "testfunc() returned false"
fi
#!/bin/bash
testfunc() {
echo "Inside function testfunc()"
return 0
}
if testfunc ; then
echo "testfunc() returned true"
else
echo "testfunc() returned false"
fi
exit 0
Output:
Inside function testfunc()
testfunc() returned true
No. A zero exit code is taken to mean "true". See this extract from the man page:
if list ;then list [ ;elif list ;then list ] ... [ ;else list ] ;fi
The list following if is executed and, if it returns a zero exit status, the list following the first then is
executed.
Ah, ok... Is that because the non-empty string is evaluated as 'true', or does it mean that non-zero will be evaluated as 'false'?
I came across something that said that function return values are much like exit codes, so I'm guessing that they're not intended to be used to return the "results" of executing the function. How then would you normally define and use a function to return a boolean value?