1: #!/bin/ksh
2: # Example 17
3:
4: # Shell idioms: multiple ways to accomplish
5: # common tasks
6:
7: # For example, test the first character in a string
8:
9: var=$1
10: echo "var=\"$var\""
11:
12: # Use 'cut' - works everywhere, but uses an an extra process
13: # for a trivial job.
14: echo
15: echo "Using 'cut'"
16: if [ "`echo $var | cut -c1`" = "/" ] ; then
17: echo "starts with /"
18: else
19: echo "doesn't start with /"
20: fi
21:
22: # Use 'case' with a pattern. Works everywhere.
23: echo
24: echo "Using 'case'"
25: case $var in
26: /*) echo "starts with /" ;;
27: *) echo "doesn't start with /" ;;
28: esac
29:
30: # Use POSIX variable truncation - works with ksh and bash and POSIX-compliant sh
31: # Dave Taylor in "Wicked Cool Shell Scripts" likes this one.
32: echo
33: echo "Using POSIX variable truncation"
34: if [ "${var%${var#?}}" = "/" ]; then
35: echo "starts with /"
36: else
37: echo "doesn't start with /"
38: fi
39:
40: # Use ksh/bash pattern template match inside of [[ ]]
41: echo
42: echo "Using ksh/bash pattern match in [[ ]]"
43: if [[ $var = /* ]]; then
44: echo "starts with /"
45: else
46: echo "doesn't start with /"
47: fi
48:
49: # Use ksh (93 and later) and bash variable substrings
50: echo
51: echo "Using ksh93/bash variable substrings"
52: if [ "${var:0:1}" = "/" ]; then
53: echo "starts with /"
54: else
55: echo "doesn't start with /"
56: fi
| last modified 22/03/2012 | Introduction | Table of Contents (frame/no frame) |
Printable (single file) |
© Dartmouth College |