Technical skill

Bash syntax: Shell Functions

Give repeated commands a name

If you type the same group of commands often, you can give that group a name and run it as one unit. In Bash, this is called a function. Functions can live in a script or in an interactive shell. The commands inside the braces are the function body; Bash runs them when you call its name. One common form is:

function_name() {
  commands
}

Bash also accepts the optional function keyword before the name. A short wrapper can collect a repeated operation:

push() {
  git push
}

After this definition, calling push runs git push. Unless the body explicitly returns or exits, the function's status is the status of its last command. Here a failed git push remains a failure for the caller; the wrapper does not make it succeed.

Pass information into a function

A function call temporarily sets positional parameters for that call. $1 is the first argument, $# counts the arguments, and "$@" preserves them as separate words. This function expects exactly one commit message:

commit() {
  git commit -m "$1"
}
commit "fix typo in usage text"

The quotes keep the message with spaces together as one value. A more defensive version checks for a missing or extra argument:

commit() {
  if (($# != 1)); then
    printf 'usage: commit MESSAGE\n' >&2
    return 2
  fi
  local message=$1
  git commit -m "$message"
}

The function sends usage information to standard error, the separate stream for messages and errors, and returns status 2 for the wrong number of arguments. On the normal path, its status comes from git commit. local limits message to the function. Bash uses dynamic scoping for locals: a function called from inside this one can see the caller's local variable if it uses the same name. Clear, specific names help prevent collisions.

Return results without ending the script

return ends a function with an integer status; it does not return arbitrary string data. Use standard output for data a caller wants to capture, for example result=$(some_function). Send diagnostics to standard error so they do not get mixed into that value. exit ends the shell process. Using it inside a function stops the whole script rather than only that function.

A function called directly runs in the current shell. A function placed in a pipeline or started as a background job may run in a subshell, a child shell with its own copy of state. Direct changes to the current shell, such as cd or changing an option, affect later commands. Make that side effect clear in the function's purpose.

Interactive exercises

Materials

Skillsets
Skillset Devops preview
image descriptionDevops
by Ajay Kumar
2004 users
Skillset Linux administrator preview
image descriptionLinux administrator
by Infinite Education
3080 users
Skillset Devops preview
image descriptionDevops
by Dio
3 users
Do you know that ...?
Any useful or interesting facts about the skill. Any peace of information would be useful