带有简单标志的脚本



假设我有这个简单的脚本

#! /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]

那么,在脚本中添加"flag"检查的最简单方法是什么呢?

感谢

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

这种更简单的方法可能也是可行的:

prog=head
for i in "$@"
do
    test "$i" = -f && prog=tail
done
$prog "$1" "$2"

解析选项时,我通常使用"case"语句:

case "$1" in
    -f) call=tail ; shift ;;
    *)  call=head ;;
esac
$call "$1" "$2"

记住引用位置参数。它们可能包含带有空格的文件名或目录名。

如果您可以使用例如bash而不是Bourne shell,则可以使用例如getopts内置命令。有关更多信息,请参阅bash手册页。

最新更新