O'Reilly logo

Linux and Unix Shell Programming by David Tansley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.5. Testing the values returned by a function

To test a value returned by a called function you can use the last status command directly after the function is called from your script. For example:

check_it_is_a_directory $FILENAME # this is the function call and check 
if [ $? = 0 ] # use the last status command now to test 
then 
  echo "All is OK" 
else 
  echo " Something went wrong!" 
fi

A much better way is to use an if statement when testing on either a return 0 or a return 1 value. Enclosing the function call with an if statement makes better logical reading. For example:

if check_it_is_a_directory $FILENAME; then 
  echo "All is OK" 
  # do something ?? 
else 
  echo "Something went wrong !" 
  # do something ?? 
fi

If the function is going to echo out ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required