Text-only Table of Contents (frame/ no frame)
(20) Conditional test examples Previous Top Next

Conditional Test Examples

As with most aspects of shell scripting, there are usually several possible ways to accomplish a task. Certain idioms show up commonly. These are five ways to examine and branch on the initial character of a string.
Use case with a pattern:
case $var in
/*) echo "starts with /" ;;
Works in all shells, and uses no extra processes

Use `cut`:
if [ "`echo $var | cut -c1`" = "/" ] ; then .
Works in all shells, but inefficiently uses a pipe and external process for a trivial task.

Use POSIX variable truncation:
if [ "${var%${var#?}}" = "/" ]; then
Works with ksh, bash and other POSIX-compliant shells. Not obvious if you have not seen this one before. Fails on old Bourne shells. Dave Taylor in "Wicked Cool Shell Scripts" likes this one.

Use POSIX pattern match inside of [[...]]:
if [[ $var = /* ]]; then
Works with ksh, bash and other POSIX-compliant shells. Note that you must use [[...]] and no quotes around the pattern. Less detail
The [[...]] syntax is handled internally by the shell and can therefore interpret "wildcard" patterns differently than an external command. An unquoted wildcard is interpreted as a pattern to be matched, while a quoted wildcard is taken literally. The [...] syntax, even if handled internally, is treated as though it were external for backward compatability. This requires that wildcard patterns be expanded to matching filenames.

Use ksh (93 and later) and bash variable substrings:
if [ "${var:0:1}" = "/" ]; then
ksh93 and later versions, and bash, have a syntax for directly extracting substrings by character position. ${varname:start:length}

Example: ex17 display, text

Previous Top Next


flow-control-ex.src  last modified Mar 11, 2005 Introduction Table of Contents
(frame/no frame)
Printable
(single file)
© Dartmouth College