2012-07-11 2 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" 

것은 인용 기억을 위치 매개 변수 파일 이름이나 디렉토리 이름에 공백이있을 수 있습니다.

예 : Bourne 쉘 대신 bash를 사용하면 예를 들어 다음과 같이 사용할 수 있습니다. getopts 내장 명령. 자세한 정보는 bash man 페이지를 참조하십시오.