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

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

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

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

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

Administrator's avatar
Administrator committed
20 21
echo 'for arg in $@ (without double quotes)'

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

Administrator's avatar
Administrator committed
26 27
echo 'for arg in "$@" (with double quotes)'

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

Administrator's avatar
Administrator committed
32 33
echo 'for arg in $* (without double quotes)'

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

Administrator's avatar
Administrator committed
38 39
echo 'for arg in "$*" (with double quotes)'

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

IFS="-"

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

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

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

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

cd "$oldpwd"
Administrator's avatar
Administrator committed
59

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