Intermediate · 8 min · practise every command in the built-in terminal

Functions in Bash

Define a function

# Method 1
function greet() {
    echo "Hello, $1!"
}

# Method 2 (POSIX compatible)
greet() {
    echo "Hello, $1!"
}

# Call it
greet "IVski"
greet "World"

Function arguments

create_file() {
    local filename="$1"       # local = only accessible inside function
    local content="$2"
    echo "$content" > "$filename"
    echo "Created: $filename"
}

create_file "test.txt" "Hello World"

Return values

Bash functions don't return values like other languages. They can:

  1. Print output (capture with $())
  2. Return an exit code (0-255)
get_date() {
    echo $(date +%Y-%m-%d)
}

TODAY=$(get_date)
echo "Today: $TODAY"

# Return exit code
file_exists() {
    [ -f "$1" ]
}  # Returns 0 if true, 1 if false

if file_exists README.txt; then
    echo "Found it!"
fi

Practical example

#!/bin/bash
set -e

log() {
    echo "[$(date +%H:%M:%S)] $1"
}

backup() {
    local src="$1"
    local dest="$2"
    log "Backing up $src to $dest"
    cp -r "$src" "$dest"
    log "Done!"
}

backup ~/documents /tmp/doc-backup

Practice tasks

  1. Write a function called 'greet' that takes a name as argument and prints 'Hello NAME!'
  2. Call your greet function again with a different name
  3. Write a function with no arguments that prints a fixed message

Commands in this lesson

Shell Scripting