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
}
标签:function,shell,getopts,echo,exit,func,usage,orgs,模板
From: https://www.cnblogs.com/xwjh/p/17146140.html