|home| |posts| |projects| |cv| |bookmarks| |github|

How to Write Shell Scripts

Let's start with the code:

#!/bin/bash

set -e

function cmd_no_args() {
    echo "this is a command without args"
}

function cmd_with_args() {
    echo "this is a command with args"
    echo "number of args:" $#
    for a in "$@"
    do
        echo $a
    done
}

function help() {
    echo "usage: $0 command [arg0..argN]"
    echo "commands:"
    echo "  help           print this message"
    echo "  cmd_no_args    run a command without arguments"
    echo "  cmd_with_args  run a command with arguments"
}

case $1 in
    cmd_no_args|cmd_with_args|help)
        ;;
    *)
        [[ ! -z "$1" ]] && echo "unknown command '$1'"
        echo "run '$0 help' to see usage"
        exit 1
        ;;
esac

"$@"

Now let's break it down.

The script consists of multiple commands.

Each command is represented by a function.

When the script is run, the first argument of the script is the command and the rest of the arguments are passed to the function which is named the same as the command.

i.e. if the script is run like this:

./myscript.sh cmd_with_args "a b c" x y z

the function cmd_with_args will be called with the arguments "a b c" x y z.

Examples

No args

./myscript.sh
run './myscript.sh help' to see usage

Wrong command

./myscript.sh wrong
unknown command 'wrong'
run './myscript.sh help' to see usage

help command

./myscript.sh help
usage: ./myscript.sh command [arg0..argN]
commands:
  help           print this message
  cmd_no_args    run a command without arguments
  cmd_with_args  run a command with arguments

Command without args

./myscript.sh cmd_no_args
this is a command without args

Command with args

./myscript.sh cmd_with_args "arg with spaces in it" arg1 arg2 arg3
this is a command with args
number of args: 4
arg with spaces in it
arg1
arg2
arg3