Two ways to write a function
The portable form of a function definition is a name followed by empty parentheses and a compound command, usually a group in braces. Bash also accepts the keyword form, function name. Both define the same thing, but the parenthesis form works in every POSIX shell, so it is the one to prefer in scripts you plan to share. The braces need a space after the opening brace, and the last command needs a semicolon or a newline before the closing brace.
greet() {
echo "hello $1"
}
greet WorldRunning that block prints hello World. The definition itself prints nothing. It only records the function under the name greet, and the call on the last line runs it. The body is ordinary shell code, so every feature in the earlier modules, including pipelines, redirections, and expansions, works inside it.
Arguments belong to the function
Inside a function, the positional parameters $1 through $9, ${10} and higher, $#, and "$@" describe the arguments of the function call. They do not describe the arguments of the script that contains it. The script name in $0 is unchanged, but the numbered parameters are replaced for the duration of the call and restored when the function returns.
show() { echo "count=$# first=$1"; }
show alpha beta
showThe first call prints count=2 first=alpha. The second call prints count=0 first=, because $1 is unset and expands to nothing. Quote "$@" when you pass arguments along, because it keeps every argument as its own word, including arguments that contain spaces. The unquoted form splits them again.
return sets a status, not a value
return N ends the function and sets its exit status to N. Only the values 0 to 255 are meaningful, because the status is one byte. Without an argument, return uses the status of the last command that ran. A function that makes a decision is written as a test that returns zero for yes and non-zero for no, and the caller uses the function directly in an if or with && and ||.
is_even() { (( $1 % 2 == 0 )); }
is_even 4 && echo "4 is even"
is_even 3 || echo "3 is not even"Both lines print a message. The first is_even call returns zero, so the echo runs. The second returns one, so the || branch runs. The arithmetic command (( )) already sets the status from its result, so the function needs no extra return.
exit inside a function ends the whole shell, or the whole script, not just the function. Use return when you only want to leave the function. In an interactive terminal, a stray exit in a function closes the terminal session.
Functions print text, they do not return it
A function cannot return a string. It can only set a number through return. To give text back, it prints the text to standard output, and the caller captures that output with command substitution. Command substitution removes trailing newlines, so the value you get back has no final newline.
shout() { echo "${1^^}"; }
loud=$(shout hello)
echo "$loud"The function prints HELLO, the substitution captures it into loud, and the last line prints it again. Because the function writes to standard output, anything else it prints, such as a progress message, also ends up in the captured value. Send diagnostic messages to standard error with >&2 so that they do not mix with the result.
Functions run in the current shell
Unlike an external program, a function runs in the shell that defines it. It does not get its own process, so it can read and change ordinary shell variables, and it can change the working directory with cd. The effect stays after the function returns. This is useful and dangerous in equal measure, which is why later units cover local variables.
A function also lives only in the shell that defined it. A child bash process does not see it unless you export it, so a function in your terminal is not available to a script that you run from the same terminal. Put the definition in a file and source it with . when you need it in more than one place.
Inspecting and removing functions
Three tools help you inspect a function. type greet reports that the name is a function. declare -f greet prints its full definition, which is useful when you forget what a function does. unset -f greet removes it. The lab for this unit asks you to write a small file of functions and test them in a fresh shell, so that you practice defining and calling them without relying on your interactive session.
greet() { echo "hello $1"; }
type greet
declare -f greet
unset -f greet
type greetThe first type call reports a function, and declare -f prints the definition. After unset -f, the last type call fails with a message that the name is not found. Keep this sequence in mind: definition, call, inspection, removal. You will use all four when you debug scripts that grow past a few dozen lines.