When your program isn't working properly(WHEN, not if), you can then put in little debug notes to yourself in the approximate section you think is broken. If you suspect a function is not working, then all you have to verify is
The first part, from the first "printmessage()" all the way through the final '}', is the function definition. It only defines what the function does, when you decide to call it. It does not DO anything, until you actually say "I want to call this function now".printmessage() { echo "Hello, this is the printmessage function" } printmessage
You call a function in ksh, by pretending it is a regular command, as shown above. Just have the function name as the first part of your line. Or any other place commands go. For example,
Remember: Just like its own separate shellscript. Which means if you access "$1" in a function, it is the first argument passed in to the function, not the shellscript.echo The message is: `printmessage`
This same type of modularity can be achived by making separate script files, instead of functions. In some ways, that is almost preferable, because it is then easier to test each part by itself. But functions run much faster than separate shellscripts.
A nice way to start a large project is to start with multiple, separate shellscripts, but then encapsulate them into functions in your main script, once you are happy with how they work.
'exit' will exit the entire script, whether it is in a function or not.
'return' will just quit the function. Like 'exit', however, it can return
the default "sucess" value of 0, or any number from 1-255 that you specify.
You can then check the return value of a function, just in the same way you
can check the return value of an external program, with the $?
variable.
# This is just a dummy script. It does not DO anything fatal(){ echo FATAL ERROR # This will quit the 'fatal' function, and the entire script that # it is in! exit } lessthanfour(){ if [[ "$1" = "" ]] ; then echo "hey, give me an argument" ; return 1; fi # we should use 'else' here, but this is just a demonstration if [[ $1 -lt 4 ]] ; then echo Argument is less than 4 # We are DONE with this function. Dont do anything else in # here. But the shellscript will continue at the caller return fi echo Argument is equal to or GREATER than 4 echo We could do other stuff if we wanted to now } echo note that the above functions are not even called. They are just echo defined
A bare "return" in a shellscript is an error. It can only be used inside a function.
#!/bin/sh # same in /bin/sh, or /bin/ksh testing(){ echo sub: var starts as $var var=2 echo sub: var is now $var } var=1 echo var starts as $var, before function testing echo var after function is now $var