【问题标题】:script with simple flag带有简单标志的脚本
【发布时间】:2012-07-11 15:33:16
【问题描述】:
假设我有这个简单的脚本
#! /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]
那么在我的脚本中添加“标志”检查的最简单方法是什么?
谢谢
【问题讨论】:
标签:
shell
arguments
flags
【解决方案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"
【解决方案2】:
我通常在解析选项时使用“case”语句:
case "$1" in
-f) call=tail ; shift ;;
*) call=head ;;
esac
$call "$1" "$2"
记得引用位置参数。它们可能包含带空格的文件名或目录名。
如果你可以使用例如bash 而不是 Bourne shell,您可以使用例如getopts 内置命令。有关详细信息,请参阅 bash 手册页。