假设我有这个简单的脚本
#! /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'检查的最简单方法是什么?
由于
答案 0 :(得分:1)
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"
答案 1 :(得分:1)
解析选项时,我通常会选择“case”语句:
case "$1" in
-f) call=tail ; shift ;;
*) call=head ;;
esac
$call "$1" "$2"
记得引用位置参数。它们可能包含带空格的文件名或目录名。
如果你可以使用例如bash而不是Bourne shell,你可以使用例如getopts内置命令。有关更多信息,请参阅bash手册页。