5-parameters.sh 1.11 KB
Newer Older
Tilman Kranz's avatar
Tilman Kranz committed
1
#!/bin/sh
Tilman Kranz's avatar
Tilman Kranz committed
2
# Evaluating the commandline arguments of a script.
3

Tilman Kranz's avatar
Tilman Kranz committed
4 5 6 7
name=$(basename "$0" .sh)
dir=$(readlink -f "$(dirname "$0")")
oldpwd=$PWD

8 9 10 11 12
if ! cd "$dir" ; then
    echo "Could not change to directory \"$dir\", aborted." >&2
    exit 1
fi

Tilman Kranz's avatar
Tilman Kranz committed
13
echo "This is example script \"$name\" (PWD: $PWD)."
14

Tilman Kranz's avatar
Tilman Kranz committed
15 16 17 18 19
if test -z "$*" ; then
    echo "Try me like this: $0 foo \"bar baz\" --blah"
    exit 1
fi

20 21
echo 'for arg in $@ (without double quotes)'

Tilman Kranz's avatar
Tilman Kranz committed
22 23 24 25
for arg in $@ ; do
    echo "    arg=\"$arg\""
done

26 27
echo 'for arg in "$@" (with double quotes)'

Tilman Kranz's avatar
Tilman Kranz committed
28 29 30 31
for arg in "$@" ; do
    echo "    arg=\"$arg\""
done

32 33
echo 'for arg in $* (without double quotes)'

Tilman Kranz's avatar
Tilman Kranz committed
34 35 36 37
for arg in $* ; do
    echo "    arg=\"$arg\""
done

38 39
echo 'for arg in "$*" (with double quotes)'

Tilman Kranz's avatar
Tilman Kranz committed
40 41 42 43 44 45
for arg in "$*" ; do
    echo "    arg=\"$arg\""
done

IFS="-"

46 47
printf 'for arg in "$*" (with double quotes and IFS="%s")\n' "$IFS"

Tilman Kranz's avatar
Tilman Kranz committed
48 49 50 51
for arg in "$*" ; do
    echo "    arg=\"$arg\""
done

52 53
printf 'for arg in "\$@" (with double quotes and IFS="%s")\n' "$IFS"

Tilman Kranz's avatar
Tilman Kranz committed
54 55 56 57 58
for arg in "$@" ; do
    echo "    arg=\"$arg\""
done

cd "$oldpwd"
Tilman Kranz's avatar
Tilman Kranz committed
59

Tilman Kranz's avatar
Tilman Kranz committed
60
# @Test foo "bar baz" --blah
61 62
# syntastic=off
# vim: ai et sts=4 ts=4 sw=4 nospell