Reputation: 9793
Suppose I have this simple script
#! /bin/sh
if [ $# -ne 2 ]
then
echo "Usage: $0 arg1 arg2"
exit 1
fi
head $1 $2
## But this is supposed to be:
## if -f flag is set,
## call [tail $1 $2]
## else if the flag is not set
## call [head $1 $2]
So what's the simplest way to add a 'flag' checking to my script?
Thanks
Upvotes: 0
Views: 218
Reputation: 11075
I usually go for the "case" statement when parsing options:
case "$1" in
-f) call=tail ; shift ;;
*) call=head ;;
esac
$call "$1" "$2"
Remember to quote the positional parameters. They might contain file names or directory names with spaces.
If you can use e.g. bash instead of Bourne shell, you can use e.g. the getopts built-in command. For more information see the bash man page.
Upvotes: 1
Reputation: 26501
fflag=no
for arg in "$@"
do
test "$arg" = -f && fflag=yes
done
if test "$fflag" = yes
then
tail "$1" "$2"
else
head "$1" "$2"
fi
This simpler approach might also be viable:
prog=head
for i in "$@"
do
test "$i" = -f && prog=tail
done
$prog "$1" "$2"
Upvotes: 1