Functions

Authors

Alex Razoumov

Marie-Hélène Burle

As in programming language, Bash functions are blocks of code that can be accessed by their names.

Function definition

Syntax

You define a new function with the following syntax:

name() {
    command1
    command2
    ...
}

Example

greetings() {
  echo hello
}

Storing functions

You can define a new function directly in the terminal. Such function would however only be available during your current session. Since functions contain code that is intended to be run repeatedly, it makes sense to store function definitions in a file. Before functions become available, the file needs to be sourced (e.g. source file.sh).

A convenient file is ~/.bashrc. The file is automatically sourced every time you start a shell so your functions will always be defined and ready for use.

Example

Let’s write a function called combine that takes all the files we pass to it, copies them into a randomly named directory, and prints that directory to the terminal:

combine() {
  if [ $# -eq 0 ]; then
    echo "No arguments specified. Usage: combine file1 [file2 ...]"
    return 1                # Return a non-zero error code
  fi
  dir=$RANDOM$RANDOM
  mkdir $dir
  cp $@ $dir
  echo look in the directory $dir
}

Your turn:

Write a function to swap two file names.
Add a check that both files exist before renaming them.

Here is a video of a previous version of this workshop.