#!/bin/ksh # Example 17 # Shell idioms: multiple ways to accomplish # common tasks # For example, test the first character in a string var=$1 echo "var=\"$var\"" # Use 'cut' - works everywhere, but uses an an extra process # for a trivial job. echo echo "Using 'cut'" if [ "`echo $var | cut -c1`" = "/" ] ; then echo "starts with /" else echo "doesn't start with /" fi # Use 'case' with a pattern. Works everywhere. echo echo "Using 'case'" case $var in /*) echo "starts with /" ;; *) echo "doesn't start with /" ;; esac # Use POSIX variable truncation - works with ksh and bash and POSIX-compliant sh # Dave Taylor in "Wicked Cool Shell Scripts" likes this one. echo echo "Using POSIX variable truncation" if [ "${var%${var#?}}" = "/" ]; then echo "starts with /" else echo "doesn't start with /" fi # Use ksh/bash pattern template match inside of [[ ]] echo echo "Using ksh/bash pattern match in [[ ]]" if [[ $var = /* ]]; then echo "starts with /" else echo "doesn't start with /" fi # Use ksh (93 and later) and bash variable substrings echo echo "Using ksh93/bash variable substrings" if [ "${var:0:1}" = "/" ]; then echo "starts with /" else echo "doesn't start with /" fi