Skip to content

Functions, arguments and set -e

AdvancedLesson 35 of 6610 min

Fix a deploy script that deletes the live site when a step fails: add set -e, wrap the work in a function and pass it arguments with $1 and "$@".

deploy.sh puts a new version of a website live. Read it first:

cat deploy.sh
ls site

There's a bug: the new build is in site/dist, but the script copies build, which doesn't exist. Worse, a script carries on after a command fails. So cp fails, then rm -rf live deletes the live site anyway, and mv has nothing to move. Run it if you like, then look at ls site, and press Reset to get the site back.

set -e: stop at the first failure

set -e near the top tells bash to stop the script as soon as a command fails. It's the first line many people add to every script:

#!/bin/bash
set -e

Commands in an if test, or before && and ||, are allowed to fail, because you're already checking them. set -u (stop on a variable that was never set) and set -o pipefail (a pipeline fails if any part fails) are often added too.

Arguments: $1 and "$@"

A script gets the words typed after its name: $1 is the first, $2 the second, $# how many there are, and "$@" all of them, each kept whole. So ./deploy.sh dist can say which folder to deploy instead of having it written into the script.

Functions

A function is a command you define yourself. It gets its own $1, $2 and "$@", and return ends it with an exit code, like exit does for a script. local keeps a variable inside the function:

greet() { local name="$1"; echo "Hello, $name"; }
greet Ana

In a script, define the function first, then call it, passing on the script's own arguments with "$@":

deploy() {
  local from="$1"
  if [ -z "$from" ]; then
    echo "usage: deploy.sh FOLDER" >&2
    return 1
  fi
  ...
}

deploy "$@"

With set -e, a function that returns 1 stops the script too.

Your turn

Rewrite deploy.sh so that (1) it stops at the first failed command (set -e), and (2) the work is in a function, deploy, that takes the folder to deploy as its first argument and prints a usage message to the error output and fails when there isn’t one. Then deploy the new site for real with ./deploy.sh dist.

Next