Skip to content
shellhacks.dev
Shell Scripting

Test for a prefix without double brackets

Test for a prefix in POSIX sh with a case pattern such as release-*), which works in dash and every other shell where double brackets are a syntax error.

1 min read
Summarize in AI

A script that runs under #!/bin/sh cannot use [[ $s == pre* ]], so a prefix test needs the construct every POSIX shell has.

Shell
s=release-2.4
case $s in
  release-*) echo "starts with release-" ;;
  *) echo "no match" ;;
esac
Text
starts with release-
Shell
s=release-2.4
if [[ $s == release-* ]]; then echo yes; fi
Text
main.sh: 2: [[: not found

Each case pattern is matched with the shell's pattern matching rules, so a trailing star means "anything after this". The construct is part of the POSIX shell command language, and unlike [, it needs no quoting of the glob. The second run shows what dash does with double brackets on Debian 12.

Pattern matching in case is a glob, not a regular expression, and an unquoted variable on the pattern side is itself treated as a pattern. Quote it, as in "$prefix"*, when it can contain a star or a question mark.

Share

More snippets

Shell Scripting

Check if a command exists in POSIX sh

Check that a command exists with command -v in POSIX sh. It is a builtin, it sees functions and builtins, and which does not.

1 min read
Shell Scripting

Replace an array with positional parameters

POSIX sh has no arrays, but set -- a b c turns the positional parameters into one, and "$@" expands each element as its own word without splitting.

1 min read
Shell Scripting

Get a substring in POSIX sh

POSIX sh has no ${v:2:3}. Build a substring from two prefix strips instead, or use cut when a subprocess is acceptable. Both run in dash.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.