shell getopts 的使用模板
demo1
#!/bin/bash
function usage() {
echo "Usage: $0 -s FUNCTION -n NAME"
}
while getopts ":s:n:" opt; do
case ${opt} in
s )
func=$OPTARG
;;
n )
name=$OPTARG
;;
\? )
echo "Invalid option: $OPTARG" 1>&2
usage
exit 1
;;
: )
echo "Option -$OPTARG requires an argument." 1>&2
usage
exit 1
;;
esac
done
if [[ -z "$func" ]]; then
echo "Function is required." 1>&2
usage
exit 1
fi
if [[ "$func" == "func1" ]]; then
func1 "$name"
elif [[ "$func" == "func2" ]]; then
func2 "$name"
else
echo "Invalid function: $func" 1>&2
usage
exit 1
fi
function func1() {
echo "Executing func1 with name=$1"
}
function func2() {
echo "Executing func2 with name=$1"
}
demo2
#!/bin/bash
function=""
orgs=""
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-func|--function)
function="$2"
shift # past argument
shift # past value
;;
--orgs)
orgs="$2"
shift # past argument
shift # past value
;;
*) # unknown option
echo "Unknown option: $key"
exit 1
;;
esac
done
if [ "$function" == "appname" ]; then
appname "$orgs"
else
echo "Unknown function: $function"
exit 1
fi
appname() {
echo "Running appname with orgs: $1"
# do something with the orgs parameter
}
demo3
#!/bin/bash
function usage {
echo "Usage: $0 [-f|--function FUNCTION] [-o|--orgs ORGS]"
echo ""
echo "Options:"
echo "-f, --function Function to run"
echo "-o, --orgs Arguments to pass to function"
}
while getopts "f:o:-:" opt; do
case "${opt}" in
f | function)
func=${OPTARG}
;;
o | orgs)
orgs=${OPTARG}
;;
-)
case "${OPTARG}" in
function=*)
func=${OPTARG#*=}
;;
orgs=*)
orgs=${OPTARG#*=}
;;
*)
echo "Invalid option: --${OPTARG}"
usage
exit 1
;;
esac
;;
*)
usage
exit 1
;;
esac
done
if [ -z "${func}" ] || [ -z "${orgs}" ]; then
usage
exit 1
fi
echo "Running function '${func}' with arguments '${orgs}'"