bash에서 getopts를 사용하는 방법의 예
전화하고 싶습니다myscript
다음과 같은 방식으로 파일:
$ ./myscript -s 45 -p any_string
또는
$ ./myscript -h #should display help
$ ./myscript #should display help
제 요구 사항은 다음과 같습니다.
getopt
.- 그것을 하세요.
-s
존재함, 오류를 반환하지 않을 경우 - 을확합다 의 값을 합니다.
-s
45 또는 90입니다. - 다.
-p
하며, 이 있습니다. - 가 " " " 라고 입력한
./myscript -h
아니면 그냥./myscript
help를 표시합니다.
지금까지 시도한 코드는 다음과 같습니다.
#!/bin/bash
while getopts "h:s:" arg; do
case $arg in
h)
echo "usage"
;;
s)
strength=$OPTARG
echo $strength
;;
esac
done
하지만 그 코드를 사용하면 오류가 발생합니다.와 Bash로 하는방법과로방법과.getopt
?
#!/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}"
예제 런:
$ ./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
원래 코드의 문제는 다음과 같습니다.
h:
안 가 있을 것으로 되므로 그냥 안되곳는매에변개수그있가을로예것므그로, ▁just▁로 변경하십시오.h
)(론없음콜)- 기대하는 바야흐로
-p any_string
추가해야 .p:
합니다.
으로 기적으로.:
다음은 인수가 필요하다는 것을 의미합니다.
기본 getopts
는 다음을 참조하십시오.man bash
):
getopts OPTSTRING VARNAME [ARGS...]
위치:
OPTSTRING
문자열로, " " " " 입니다.h
션확을 합니다.-h
매개 변수 없음, 지원되지 않는 옵션에 오류를 표시합니다.h:
션확을 합니다.-h
매개 변수 포함, 지원되지 않는 옵션에 오류를 표시합니다.abc
합니다.-a
,-b
,-c
지원되지 않는 옵션에 오류를 표시합니다.:abc
합니다.-a
,-b
,-c
지원되지 않는 옵션에 대한 소음 오류;참고: 다시 말해, 옵션 앞에 있는 콜론을 사용하면 코드의 오류를 처리할 수 있습니다.에 변에포됨이 됩니다.
?
되지 않는 옵션의 에는 지되지 옵의경우션않는원경▁in,우옵의션않supported▁the는▁case:
값이 누락된 경우
OPTARG
인수값으로 되어 있습니다.OPTERR
Bash가 오류 메시지를 표시해야 하는지 여부를 나타냅니다.
코드는 다음과 같습니다.
#!/usr/bin/env bash
usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }
[ $# -eq 0 ] && usage
while getopts ":hs:p:" arg; do
case $arg in
p) # Specify p value.
echo "p is ${OPTARG}"
;;
s) # Specify strength, either 45 or 90.
strength=${OPTARG}
[ $strength -eq 45 -o $strength -eq 90 ] \
&& echo "Strength is $strength." \
|| echo "Strength needs to be either 45 or 90, $strength found instead."
;;
h | *) # Display help.
usage
exit 0
;;
esac
done
사용 예:
$ ./foo.sh
./foo.sh usage:
p) # Specify p value.
s) # Specify strength, either 45 or 90.
h | *) # Display help.
$ ./foo.sh -s 123 -p any_string
Strength needs to be either 45 or 90, 123 found instead.
p is any_string
$ ./foo.sh -s 90 -p any_string
Strength is 90.
p is any_string
참조: Bash Hackers Wiki의 작은 getopts 튜토리얼
사용하다getopt
왜 getopt?
복잡한 명령줄 인수를 구문 분석하여 혼동을 방지하고 구문 분석 중인 옵션을 명확하게 하여 명령을 읽는 사람이 무슨 일이 일어나고 있는지 이해할 수 있도록 합니다.
getopt란 무엇입니까?
getopt
셸 프로시저에 의해 쉽게 구문 분석할 수 있도록 명령줄에서 옵션을 분할(분할)하고 합법적인 옵션을 확인하는 데 사용됩니다. GNU를 합니다.getopt(3)
이를 위한 루틴.
getopt
에는 다음과 같은 유형의 옵션이 있습니다.
- 값 없음 옵션
- 키-값 쌍 옵션
참고: 이 문서에서는 구문을 설명하는 동안 다음과 같이 설명합니다.
- 모는것 안에 있는 것.
[ ]
구문/키워드의 선택적 매개 변수입니다. <value>
자리 표시자입니다. 즉, 실제 값으로 대체해야 합니다.
용법getopt
?
구문: 첫 번째 양식
getopt optstring parameters
예:
# This is correct
getopt "hv:t::" -v 123 -t123
getopt "hv:t::" -v123 -t123 # -v and 123 doesn't have whitespace
# -h takes no value.
getopt "hv:t::" -h -v123
# This is wrong. after -t can't have whitespace.
# Only optional params cannot have whitespace between key and value
getopt "hv:t::" -v 123 -t 123
# Multiple arguments that takes value.
getopt "h:v:t::g::" -h abc -v 123 -t21
# Multiple arguments without value
# All of these are correct
getopt "hvt" -htv
getopt "hvt" -h -t -v
getopt "hvt" -tv -h
여기서 h,v,t는 옵션이고 -h -v -t는 명령줄에서 옵션을 지정하는 방법입니다.
- 'h'는 값이 없는 옵션입니다.
- 'v:'는 옵션 -v에 값이 있으며 필수 옵션임을 의미합니다.평균에 값이 있습니다.
- 't::'는 옵션 -t에 값이 있지만 선택 사항임을 의미합니다.옵션을 의미합니다.
선택적 매개 변수에서 값은 옵션과 공백으로 구분될 수 없습니다.따라서 "-t123" 예제에서 -t는 옵션 123이 값입니다.
구문: 두 번째 양식
getopt [getopt_options] [--] optstring parameters
여기서 getopt는 다섯 부분으로 나뉩니다.
- 명령 자체, 즉 getopt.
- getopt_options는 인수를 구문 분석하는 방법을 설명합니다. 단일 대시 롱 옵션, 이중 대시 옵션.
- 구문 분석할 옵션과 허용되는 짧은 옵션에서 getopt_message를 구분합니다.
- --가 발견된 직후에 수행되는 바로 가기 옵션입니다.양식 첫 번째 구문과 같습니다.
- 매개변수는 프로그램에 전달한 옵션입니다.구문 분석하고 실제 값을 설정할 옵션입니다.
예
getopt -l "name:,version::,verbose" -- "n:v::V" --name=Karthik -version=5.2 -verbose
구문: 세 번째 양식
getopt [getopt_options] -o|--options optstring [getopt_options] [--] [parameters]
여기서 getopt는 다섯 부분으로 나뉩니다.
- 명령 자체, 즉 getopt.
- getopt_options는 인수를 구문 분석하는 방법을 설명합니다. 단일 대시 롱 옵션, 이중 대시 옵션.
- 짧은 옵션(예: -o 또는 --options)입니다.Form 첫 번째 구문과 마찬가지로 옵션 "-o"와 "--"(더블 대시) 앞에 있습니다.
- 구문 분석할 옵션과 허용되는 짧은 옵션에서 getopt_message를 구분합니다.
- 매개변수는 프로그램에 전달한 옵션입니다.구문 분석하고 실제 값을 설정할 옵션입니다.
예
getopt -l "name:,version::,verbose" -a -o "n:v::V" -- -name=Karthik -version=5.2 -verbose
GETOPT_OPTIONS
getopt_param은 명령줄 매개 변수를 구문 분석하는 방법을 변경합니다.
다음은 getopt_options의 일부입니다.
옵션: -l 또는 --long 옵션
getopt 명령을 사용하면 다중 문자 옵션을 인식할 수 있습니다.여러 옵션은 쉼표로 구분됩니다.
를 들면, 들면를예,--name=Karthik
명령줄에서 전송되는 긴 옵션입니다.은 getopt 에긴 옵션사의용다같음습다니서과와 같습니다.
getopt -l "name:,version" -- "" --name=Karthik
name:이(가) 지정되었으므로 옵션에 값이 포함되어야 합니다.
옵션: -a 또는 --alternative
즉, getopt 명령은 긴 옵션이 이중 대시 '--'가 아닌 단일 대시 '-'를 가질 수 있도록 허용해야 합니다.
예를 들어,--name=Karthik
당신은 그냥.-name=Karthik
getopt -a -l "name:,version" -- "" -name=Karthik
코드가 포함된 전체 스크립트 예제:
#!/bin/bash
# filename: commandLine.sh
# author: @theBuzzyCoder
showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode
-h, -help, --help Display help
-v, -espo-version, --espo-version Set and Download specific version of EspoCRM
-r, -rebuild, --rebuild Rebuild php vendor directory using composer and compiled css using grunt
-V, -verbose, --verbose Run script in verbose mode. Will print out each step of execution.
EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}
export version=0
export verbose=0
export rebuilt=0
# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")
# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters
# are set to the arguments, even if some of them begin with a ‘-’.
eval set -- "$options"
while true
do
case "$1" in
-h|--help)
showHelp
exit 0
;;
-v|--version)
shift
export version="$1"
;;
-V|--verbose)
export verbose=1
set -xv # Set xtrace and verbose mode.
;;
-r|--rebuild)
export rebuild=1
;;
--)
shift
break;;
esac
shift
done
이 스크립트 파일 실행 중:
# With short options grouped together and long option
# With double dash '--version'
bash commandLine.sh --version=1.0 -rV
# With short options grouped together and long option
# With single dash '-version'
bash commandLine.sh -version=1.0 -rV
# OR with short option that takes value, value separated by whitespace
# by key
bash commandLine.sh -v 1.0 -rV
# OR with short option that takes value, value without whitespace
# separation from key.
bash commandLine.sh -v1.0 -rV
# OR Separating individual short options
bash commandLine.sh -v1.0 -r -V
패키지에 포함된 예제getopt
(내 대리점이 그것을 넣었습니다./usr/share/getopt/getopt-parse.bash
) 모든 사례를 다루는 것 같습니다.
#!/bin/bash
# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh
# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument 'more'
# Option b, argument ' very long '
# Remaining arguments:
# --> 'par1'
# --> 'another arg'
# --> 'wow!*\?'
# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around '$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=$(getopt -o ab:c:: --long a-long,b-long:,c-long:: \
-n 'example.bash' -- "$@")
if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi
# Note the quotes around '$TEMP': they are essential!
eval set -- "$TEMP"
while true ; do
case "$1" in
-a|--a-long) echo "Option a" ; shift ;;
-b|--b-long) echo "Option b, argument '$2'" ; shift 2 ;;
-c|--c-long)
# c has an optional argument. As we are in quoted mode,
# an empty parameter will be generated if its optional
# argument is not found.
case "$2" in
"") echo "Option c, no argument"; shift 2 ;;
*) echo "Option c, argument '$2'" ; shift 2 ;;
esac ;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
echo "Remaining arguments:"
for arg do echo '--> '"'$arg'" ; done
이미 답변이 끝났다는 것을 알고 있지만, 기록을 위해 그리고 저와 같은 요구 사항을 가진 사람들을 위해 이 관련 답변을 게시하기로 결정했습니다.코드에 코드를 설명하는 댓글이 쇄도합니다.
업데이트된 답변:
파일을 다음으로 저장getopt.sh
:
#!/bin/bash
function get_variable_name_for_option {
local OPT_DESC=${1}
local OPTION=${2}
local VAR=$(echo ${OPT_DESC} | sed -e "s/.*\[\?-${OPTION} \([A-Z_]\+\).*/\1/g" -e "s/.*\[\?-\(${OPTION}\).*/\1FLAG/g")
if [[ "${VAR}" == "${1}" ]]; then
echo ""
else
echo ${VAR}
fi
}
function parse_options {
local OPT_DESC=${1}
local INPUT=$(get_input_for_getopts "${OPT_DESC}")
shift
while getopts ${INPUT} OPTION ${@};
do
[ ${OPTION} == "?" ] && usage
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ "${VARNAME}" != "" ] && eval "${VARNAME}=${OPTARG:-true}" # && printf "\t%s\n" "* Declaring ${VARNAME}=${!VARNAME} -- OPTIONS='$OPTION'"
done
check_for_required "${OPT_DESC}"
}
function check_for_required {
local OPT_DESC=${1}
local REQUIRED=$(get_required "${OPT_DESC}" | sed -e "s/\://g")
while test -n "${REQUIRED}"; do
OPTION=${REQUIRED:0:1}
VARNAME=$(get_variable_name_for_option "${OPT_DESC}" "${OPTION}")
[ -z "${!VARNAME}" ] && printf "ERROR: %s\n" "Option -${OPTION} must been set." && usage
REQUIRED=${REQUIRED:1}
done
}
function get_input_for_getopts {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_optional {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/[^[]*\(\[[^]]*\]\)[^[]*/\1/g" -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/[][ -]//g"
}
function get_required {
local OPT_DESC=${1}
echo ${OPT_DESC} | sed -e "s/\([a-zA-Z]\) [A-Z_]\+/\1:/g" -e "s/\[[^[]*\]//g" -e "s/[][ -]//g"
}
function usage {
printf "Usage:\n\t%s\n" "${0} ${OPT_DESC}"
exit 10
}
그런 다음 다음과 같이 사용할 수 있습니다.
#!/bin/bash
#
# [ and ] defines optional arguments
#
# location to getopts.sh file
source ./getopt.sh
USAGE="-u USER -d DATABASE -p PASS -s SID [ -a START_DATE_TIME ]"
parse_options "${USAGE}" ${@}
echo ${USER}
echo ${START_DATE_TIME}
이전 답변:
저는 최근에 일반적인 접근법을 사용해야 했습니다.저는 다음과 같은 해결책을 얻었습니다.
#!/bin/bash
# Option Description:
# -------------------
#
# Option description is based on getopts bash builtin. The description adds a variable name feature to be used
# on future checks for required or optional values.
# The option description adds "=>VARIABLE_NAME" string. Variable name should be UPPERCASE. Valid characters
# are [A-Z_]*.
#
# A option description example:
# OPT_DESC="a:=>A_VARIABLE|b:=>B_VARIABLE|c=>C_VARIABLE"
#
# -a option will require a value (the colon means that) and should be saved in variable A_VARIABLE.
# "|" is used to separate options description.
# -b option rule applies the same as -a.
# -c option doesn't require a value (the colon absense means that) and its existence should be set in C_VARIABLE
#
# ~$ echo get_options ${OPT_DESC}
# a:b:c
# ~$
#
# Required options
REQUIRED_DESC="a:=>REQ_A_VAR_VALUE|B:=>REQ_B_VAR_VALUE|c=>REQ_C_VAR_FLAG"
# Optional options (duh)
OPTIONAL_DESC="P:=>OPT_P_VAR_VALUE|r=>OPT_R_VAR_FLAG"
function usage {
IFS="|"
printf "%s" ${0}
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "-${i:0:1} $VARNAME"
done
for i in ${OPTIONAL_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
printf " %s" "[-${i:0:1} $VARNAME]"
done
printf "\n"
unset IFS
exit
}
# Auxiliary function that returns options characters to be passed
# into 'getopts' from a option description.
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# OPTIONS=$(get_options ${OPT_DESC})
# echo "${OPTIONS}"
#
# Output:
# "h:f:PW"
function get_options {
echo ${1} | sed -e "s/\([a-zA-Z]\:\?\)=>[A-Z_]*|\?/\1/g"
}
# Auxiliary function that returns all variable names separated by '|'
# Arguments:
# $1: The options description (SEE TOP)
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# VARNAMES=$(get_values ${OPT_DESC})
# echo "${VARNAMES}"
#
# Output:
# "H_VAR|F_VAR|P_VAR|W_VAR"
function get_variables {
echo ${1} | sed -e "s/[a-zA-Z]\:\?=>\([^|]*\)/\1/g"
}
# Auxiliary function that returns the variable name based on the
# option passed by.
# Arguments:
# $1: The options description (SEE TOP)
# $2: The option which the variable name wants to be retrieved
#
# Example:
# OPT_DESC="h:=>H_VAR|f:=>F_VAR|P=>P_VAR|W=>W_VAR"
# H_VAR=$(get_variable_name ${OPT_DESC} "h")
# echo "${H_VAR}"
#
# Output:
# "H_VAR"
function get_variable_name {
VAR=$(echo ${1} | sed -e "s/.*${2}\:\?=>\([^|]*\).*/\1/g")
if [[ ${VAR} == ${1} ]]; then
echo ""
else
echo ${VAR}
fi
}
# Gets the required options from the required description
REQUIRED=$(get_options ${REQUIRED_DESC})
# Gets the optional options (duh) from the optional description
OPTIONAL=$(get_options ${OPTIONAL_DESC})
# or... $(get_options "${OPTIONAL_DESC}|${REQUIRED_DESC}")
# The colon at starts instructs getopts to remain silent
while getopts ":${REQUIRED}${OPTIONAL}" OPTION
do
[[ ${OPTION} == ":" ]] && usage
VAR=$(get_variable_name "${REQUIRED_DESC}|${OPTIONAL_DESC}" ${OPTION})
[[ -n ${VAR} ]] && eval "$VAR=${OPTARG}"
done
shift $(($OPTIND - 1))
# Checks for required options. Report an error and exits if
# required options are missing.
# Using function version ...
VARS=$(get_variables ${REQUIRED_DESC})
IFS="|"
for VARNAME in $VARS;
do
[[ -v ${VARNAME} ]] || usage
done
unset IFS
# ... or using IFS Version (no function)
OLDIFS=${IFS}
IFS="|"
for i in ${REQUIRED_DESC};
do
VARNAME=$(echo $i | sed -e "s/.*=>//g")
[[ -v ${VARNAME} ]] || usage
printf "%s %s %s\n" "-${i:0:1}" "${!VARNAME:=present}" "${VARNAME}"
done
IFS=${OLDIFS}
대충 테스트한 게 아니라서 벌레가 들어갈 수도 있어요.
POSIX 7 예
또한 표준에서 예제를 확인할 가치가 있습니다. http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
aflag=
bflag=
while getopts ab: name
do
case $name in
a) aflag=1;;
b) bflag=1
bval="$OPTARG";;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
if [ ! -z "$aflag" ]; then
printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"
그런 다음 사용해 볼 수 있습니다.
$ sh a.sh
Remaining arguments are:
$ sh a.sh -a
Option -a specified
Remaining arguments are:
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain
Ubuntu 17.10에서 테스트됨sh
대시 0.5.8입니다.
getopts
그리고.getopt
매우 제한적입니다.하는 동안에getopt
전혀 사용하지 않는 것이 좋습니다. 긴 옵션을 제공합니다.반면에.getopts
다음과 같은 단일 문자 옵션만 허용합니다.-a
-b
둘 중 하나를 사용할 때 몇 가지 단점이 더 있습니다.
그래서 저는 작은 대본을 썼습니다.getopts
그리고.getopt
그것은 시작입니다, 아마도 많이 개선될 수 있을 것입니다.
업데이트 08-04-2020: 하이픈 등에 대한 지원을 추가했습니다.--package-name
.
사용법: "//script.sh 패키지 설치 --package "공백이 있는 이름" --build --build"
# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
PREVIOUS_ITEM=''
COUNT=0
for CURRENT_ITEM in "${@}"
do
if [[ ${CURRENT_ITEM} == "--"* ]]; then
printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
else
if [[ $PREVIOUS_ITEM == "--"* ]]; then
printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
else
printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
fi
fi
PREVIOUS_ITEM="${CURRENT_ITEM}"
(( COUNT++ ))
done
}
# Format argument.
function formatArgument() {
ARGUMENT="${1^^}" # Capitalize.
ARGUMENT="${ARGUMENT/--/}" # Remove "--".
ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
echo "${ARGUMENT}"
}
마크 G.의 코멘트(아드리안 프뤼휘워스의 답변 아래)에 있는 거대한 한 줄을 더 읽기 쉬운 답변으로 바꾸는 것 - 이것은 사용을 피하는 방법을 보여줍니다.getopts
선택적 인수를 가져오는 방법:
usage() {
printf "Usage: %s <req> [<-s|--sopt> <45|90>] [<-p|--popt> <string>]\n" "$0";
return 1;
};
main() {
req="${1:?$(usage)}";
shift;
s="";
p="";
while [ "$#" -ge 1 ]; do
case "$1" in
-s|--sopt)
shift;
s="${1:?$(usage)}";
[ "$s" -eq 45 ] || [ "$s" -eq 90 ] || {
usage;
return 1;
}
;;
-p|--popt)
shift;
p="${1:?$(usage)}"
;;
*)
usage;
return 1
;;
esac;
shift;
done;
printf "req = %s\ns = %s\np = %s\n" "$req" "$s" "$p";
};
main "$@"
n.caillou의 논평에 언급된 바와 같이:
옵션과 인수 사이에 공백이 없으면 실패합니다.
그러나 POSIX 호환성을 높이기 위해 (Mark G.의 다른 코멘트에서):
case "$1" in
-s*)
s=${1#-s};
if [ -z "$s" ];
shift;
s=$1;
fi
언급URL : https://stackoverflow.com/questions/16483119/an-example-of-how-to-use-getopts-in-bash
'programing' 카테고리의 다른 글
virtualenwrapper 및 Python 3 (0) | 2023.05.25 |
---|---|
부트스트랩 모달에 포함된 경우 Select2가 작동하지 않습니다. (0) | 2023.05.25 |
PostgreSQL 오류: 치명적: 역할 "사용자 이름"이 없습니다. (0) | 2023.05.25 |
jQuery를 사용하여 요소의 ID를 얻으려면 어떻게 해야 합니까? (0) | 2023.05.25 |
jquery DataTables에 대한 초기 정렬을 비활성화할 수 있는 방법이 있습니까? (0) | 2023.05.25 |