Scripting 201

Linux

HOGENT toegepaste informatica

2026-2027

Complexere scripts

Communicatie script/omgeving

Informatie uitwisselen tussen script en omgeving:

  • I/O: stdin, stdout, stderr
  • Positionele parameters: $1, $2, enz.
  • Exit-status (0-255)
  • Omgevingsvariabelen, vb:
VAGRANT_LOG=debug vagrant up

Functies in Bash

functie_naam() {
    # code
}

Een functie gedraagt zich als een commando!

  • oproepen: functie_naam arg1 arg2 arg3
  • positionele parameters: ${1}, ${2}, enz.
  • return STATUS ipv exit

Uitvoer opvangen: command substitution

Hoe kan je een functie een “waarde” laten teruggeven? Via stdout!

output=$(command arg1 arg2)

stdout van command wordt opgevangen en opgeslagen in variabele ${output}.

Scope variabelen bij functies - global

Wat is de uitvoer van dit script?

#! /usr/bin/env bash
var_a=a

foo() {
  var_b=b
  echo "${var_a} ${var_b}"
}

foo

echo "${var_a} ${var_b}"

Scope variabelen bij functies - local

Wat is de uitvoer van dit script?

#! /usr/bin/env bash
var_a=a

foo() {
  local var_b=b
  echo "${var_a} ${var_b}"
}

foo

echo "${var_a} ${var_b}"

Functies in Bash: voorbeeld

# Usage: copy_iso_to_usb ISO_FILE DEVICE
# Copy an ISO file to a USB device, showing progress with pv (pipe viewer)
# e.g. copy_iso_to_usb FedoraWorkstation.iso /dev/sdc
copy_iso_to_usb() {
  local iso="${1}"
  local destination="${2}"
  local iso_size

  iso_size=$(stat -c '%s' "${iso}")

  printf "Copying %s (%'dB) to %s\n" \
    "${iso}" "${iso_size}" "${destination}"

  dd if="${iso}" \
    | pv --size "${iso_size}" \
    | sudo dd of="${destination}"
}

Parameter substitution

Zie Parameter Substitution in de Advanced Bash-Scripting Guide.

var="Hello world!"
echo "${other_var:-default}" # default
echo "${var,,}"              # hello world! (lowercase)
echo "${var^^}"              # HELLO WORLD!
echo "${var//o/a}"           # Hella warld!
echo "${var:2}"              # llo world!
echo "${var:6:5}"            # world

Parameter substitution (2)

Verwijder patroon van begin/einde van een string:

path="some/path/archive.tar.gz"
echo "${path#*/}"   # path/archive.tar.gz
echo "${path##*/}"  # archive.tar.gz
echo "${path%.*}"   # some/path/archive.tar
echo "${path%%.*}"  # some/path/archive

Case (1)

case EXPR in
  PATROON1)
    # ...
    ;;
  PATROON2)
    # ...
    ;;
  *)
    # ...
    ;;
esac

PATROON in globbing syntax! (man 7 glob)

Case (2)

option="${1}"

case "${option}" in
  -h|--help|'-?')
    usage
    exit 0
    ;;
  -v|--verbose)
    verbose=y
    shift
    ;;
  -*)
    printf 'Unrecognized option: %s\n' "${option}"
    usage
    exit 1
    ;;
esac

Tips

  • Zet positionele parameters om in beschrijvende namen
  • Maak lijnen niet te lang (gebruik \ op het einde van een regel)
  • Gebruik “lange” opties: maakt script leesbaarder
  • Gebruik lokale variabelen in functies
  • Deel script op in (herbruikbare) functies