Almquist shell - The quick guide

October 20, 2023 Shell
Quickly find recipes to resolve shell tasks.

Almquist shell written as a BSD-licensed replacement for the Bourne Shell; often used in resource-constrained environments.

Scripting

Check tutorial for detailed syntax.

Array interation

Array is not part of the POSIX shell specification, this is a hack.

range="a b c 1 2 3"
for e in $range; do
    echo $e
done

Parse CLI arguments

The following snippet implements CLI arguments parsing. Options usually start with a dash, but arguments is position based. It should be useful for most scenarios. Adjust it against your own need.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# usage: script.sh -o1 abc xyz
# default values of options
opts_count=0
args_count=0
args=''
dry_run=0

# define options here
opt1=''

while :; do
  case "${1-}" in
  -h | --help)
    echo "no options or arguments"
    exit 0
    ;;

  # parse options
  --dry-run)
    dry_run=1
    ;;
  -o1 | --opt1)
    opt1="${2-}"

    opts_count=$((opts_count + 1))
    shift
    ;;

  -?*)
    echo "unrecognized option"
    exit 0
    ;;

  *)
    if [ -z "$args" ]; then
      args="${1-}"
    else
      args="${args} ${1-}"
    fi

    if [ -z "${1-}" ]; then
      break
    fi
    ;;
  esac

  if [ -n "${1-}" ]; then
    shift
  fi
done

# init arguments
arg1=''

# parse args
for arg in $args; do
  args_count=$((args_count + 1))

  # define positional arguments here
  if [ "$args_count" -eq 1 ]; then
    arg1="$arg"
  fi
done

if [ "$opts_count" -eq 0 ] && [ "$args_count" -eq 0 ]; then
  echo "no options or arguments"
fi