2011-06-10 5 views
3

위치 지정없는 인수를 쉘 스크립트에 제공 할 수있는 방법이 있습니까? 의미는 명시 적으로 어떤 종류의 플래그를 지정합니까?쉘 스크립트 인수가 아닌 위치

. myscript.sh value1 value2 
. myscript.sh -val1=value1 -val2=value2 

답변

4

getopts을 사용할 수는 있지만 사용하기가 복잡하고 긴 옵션 이름 (POSIX 버전이 아니어도 됨)을 지원하지 않기 때문에 좋지 않습니다.

환경 변수 사용을 권장하지 않습니다. 이름 충돌의 위험이 너무 많습니다. 예를 들어, 스크립트가 ARCH 환경 변수의 값에 따라 다르게 반응하고 (알지 못하더라도) ARCH 환경 변수에 반응하는 다른 스크립트를 실행하면 아마도 찾기 힘든 버그 만있을 것입니다 때때로 나타납니다.

#!/bin/sh 

usage() { 
    cat <<EOF 
Usage: $0 [options] [--] [file...] 

Arguments: 

    -h, --help 
    Display this usage message and exit. 

    -f <val>, --foo <val>, --foo=<val> 
    Documentation goes here. 

    -b <val>, --bar <val>, --bar=<val> 
    Documentation goes here. 

    -- 
    Treat the remaining arguments as file names. Useful if the first 
    file name might begin with '-'. 

    file... 
    Optional list of file names. If the first file name in the list 
    begins with '-', it will be treated as an option unless it comes 
    after the '--' option. 
EOF 
} 

# handy logging and error handling functions 
log() { printf '%s\n' "$*"; } 
error() { log "ERROR: $*" >&2; } 
fatal() { error "$*"; exit 1; } 
usage_fatal() { error "$*"; usage >&2; exit 1; } 

# parse options 
foo="foo default value goes here" 
bar="bar default value goes here" 
while [ "$#" -gt 0 ]; do 
    arg=$1 
    case $1 in 
     # convert "--opt=the value" to --opt "the value". 
     # the quotes around the equals sign is to work around a 
     # bug in emacs' syntax parsing 
     --*'='*) shift; set -- "${arg%%=*}" "${arg#*=}" "[email protected]"; continue;; 
     -f|--foo) shift; foo=$1;; 
     -b|--bar) shift; bar=$1;; 
     -h|--help) usage; exit 0;; 
     --) shift; break;; 
     -*) usage_fatal "unknown option: '$1'";; 
     *) break;; # reached the list of file names 
    esac 
    shift || usage_fatal "option '${arg}' requires a value" 
done 
# arguments are now the file names 
3

가장 쉬운 것은 환경 변수로 전달할입니다 :

 
$ val1=value1 val2=value2 ./myscript.sh 

이 CSH 변종 작동하지 않습니다,하지만 당신은 같은 쉘을 사용하는 경우는 ENV를 사용할 수 있습니다.

2

예 :

은 내가 사용하는 패턴이다

#!/bin/bash 
while getopts d:x arg 
do 
     case "$arg" in 
       d) darg="$OPTARG";; 
       x) xflag=1;; 
       ?) echo >&2 "Usage: $0 [-x] [-d darg] files ..."; exit 1;; 
     esac 
done 
shift $(($OPTIND-1)) 

for file 
do 
     echo =$file= 
done