Shell scriptの分岐、反復と終了status2 / 4
Testと分岐
[ ... ]はtest commandの別表記で、[と]の前後の空白が必要になる。-fは通常file、-rは読取り可能、-dはdirectory、-zは長さ0、文字列の=は一致、-eq/-neなどは整数の比較へ使う。
#!/bin/sh
if [ "$#" -ne 1 ]; then
printf 'usage: %s input-file\n' "$0" >&2
exit 2
fi
if [ ! -r "$1" ]; then
printf 'cannot read: %s\n' "$1" >&2
exit 1
fi
while IFS= read -r line || [ -n "$line" ]; do
case "$line" in
error:*) printf '%s\n' "$line" ;;
esac
done < "$1"
この例は引数を一つ要求し、読めるfileからerror:で始まる行を表示する。read -rはbackslashをそのまま扱い、IFS=は先頭・末尾の空白を保つ。末尾に改行のない最終行も、readが値を入れた場合に処理する。失敗時のstatus2と1は、このscriptが定めた契約である。