SORU
10 Mayıs 2013, Cuma


bash getopts nasıl kullanılır

Benim komut dosyası bash çağırırken giriş değişkeni almak istiyorum.

myscript bu şekilde dosya aramak istiyorum:

$./myscript -s 45 -p any_string

ya

$./myscript -h >>> display help
$./myscript    >>> display help

Dosya komut:

#!/bin/bash

# getopt here to get the input arguments
# check that -s exists, if not return error
# check that the value after the -s is 45 or 90
# check that the -p exists and there is an input string after
# if the user enters ./myscript -h or just ./myscript then display help

Bu kodu denedim:

#!/bin/bash

while getopts "h:s:" arg; do
  case $arg in
    h)
      echo "usage" 
      ;;
    s)
      strength=$OPTARG
      echo $strength
      ;;
  esac
done

Ama bu kod ile hata alıyorum.

Nasıl Bash ve getopt ile yapmalı?

CEVAP
11 Mayıs 2013, CUMARTESİ


#!/bin/bash

usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }

while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${s}" ] || [ -z "${p}" ]; then
    usage
fi

echo "s = ${s}"
echo "p = ${p}"

Örnek çalışır:

$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • dougownsall

    dougownsall

    7 EKİM 2007
  • PomplamooseMusic

    PomplamooseM

    28 HAZİRAN 2008
  • Tube Time

    Tube Time

    14 Mayıs 2013