2012-07-11 12 views
0

假設我有這個簡單的腳本腳本用簡單的標誌

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

那麼什麼是添加一個「標誌」檢查,我的腳本最簡單的方法?

感謝

回答

1
fflag=no 
for arg in "[email protected]" 
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 "[email protected]" 
do 
    test "$i" = -f && prog=tail 
done 

$prog "$1" "$2" 
1

我解析選項時,通常會去的 「情況」 的聲明:

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

$call "$1" "$2" 

記得引用位置參數。它們可能包含帶空格的文件名或目錄名。

如果您可以使用例如bash而不是Bourne shell,你可以使用例如getopts內置的命令。欲瞭解更多信息,請參閱bash手冊頁。