Shell tips SliTaz 5.1

SliTaz tools, receipts and boot scripts are shell scripts run by the busybox ash shell (/bin/sh). This page gathers tips to keep them fast and portable. Add yours, with a benchmark, and put the best ones first.

The rule: avoid starting a process

Starting a program costs far more than anything the shell does by itself. In a loop, every sed, grep, cut or $(...) starts a new process; a builtin or a parameter expansion does not. Most tips below come back to this.

The timings were measured on SliTaz 5.1 with busybox 1.38, on a recent x86_64 laptop: each script was run with busybox sh, best of several runs. On an old machine everything is slower, but the ratios stay. Write the test as a small script:

#!/bin/sh
for i in $(seq 1 1000); do
	echo "slitaz" | sed 's/slitaz/SliTaz/' > /dev/null
done

and time it with time sh ./test.sh.

Parameter expansion instead of sed, basename, expr

1000 loops:

The POSIX expansions work in every shell:

f=/usr/share/doc/slitaz/toolchain.txt
echo ${f##*/}     # toolchain.txt   (basename)
echo ${f%/*}      # /usr/share/doc/slitaz   (dirname)
echo ${f%.txt}    # remove a suffix
echo ${f#/usr}    # remove a prefix
echo ${#f}        # length

${var/old/new} is not POSIX: busybox ash and bash have it, a strict POSIX shell such as dash does not. Fine for SliTaz scripts; avoid it in a script meant for other systems.

Command substitution forks, even for a builtin

1000 loops:

$(...) runs its commands in a new shell process, even when it only calls echo. Assign the expansion directly. The same goes for reading a one-line file, such as a value under /sys:

read takes the first line only.

Group with { } rather than ( )

10000 loops:

{ ...; } groups commands in the current shell, ( ... ) starts a subshell. Both can share one redirection:

{ echo "line 1"; echo "line 2"; } > file

Mind the differences: inside { }, cd, variables and exit act on the script itself; inside ( ), they are lost when the subshell ends, which is sometimes what you want. { needs a space after it, and a ; or a new line before }.

grep, grep -F, awk, cut: the process is the cost

1000 loops, with busybox applets:

On a small input the choice of tool hardly matters: starting it is what takes the time. Use grep -F for a fixed string anyway: it says what you mean. The real gain is to run the tool once on the whole input instead of once per line:

# slow: one grep per package
for pkg in $list; do grep -q "^$pkg$" installed.txt && echo $pkg; done

# fast: one grep for all of them
echo "$list" | tr ' ' '\n' | grep -F -x -f installed.txt

Tests: keep them readable

1000000 loops; [ is a builtin of ash, so these differences are a fraction of a microsecond per test:

Write the test that reads best: [ -n "$var" ] and [ -z "$var" ] say what they check. Join two tests with && or ||: it is faster in ash, and the -a and -o operators of [ are marked obsolete by POSIX.

Portable habits