我想向脚本传递长参数,并参考此链接。我创建了这个 my_script:
#!/usr/bin/env bash
#
# Adapted from https://www.shellscript.sh/examples/getopt/
#
set -euo pipefail
user_type=unset
user_id=unset
country=unset
dev_env=unset
position_id=unset
usage(){
>&2 cat << EOF
Usage: $0]
[ -a | --user_type input
[ -b | --user_id input ]
[ -c | --country input ]
[ -d | --dev_env input ]
[ -e | --position_id input ]
EOF
exit 1
}
>&2 echo [$@] passed to script
args=$(getopt -a -o ha:b:c:d: --long help,user_type:,user_id:,country:,dev_env:,position_id: -- "$@")
if [[ $? -gt 0 ]]; then
usage
fi
>&2 echo getopt creates [${args}]
eval set -- ${args}
while :
do
case $1 in
-a | --user_type) user_type=$2 ; shift 2 ;;
-b | --user_id) user_id=$2 ; shift 2 ;;
-h | --help) usage ; shift ;;
-c | --country) country=$2 ; shift 2 ;;
-d | --dev_env) dev_env=$2 ; shift 2 ;;
-e | --position_id) position_id=$2 ; shift 2 ;;
# -- means the end of the arguments; drop this, and break out of the while loop
--) shift; break ;;
*) >&2 echo Unsupported option: $1
usage ;;
esac
done
if [[ $# -eq 0 ]]; then
usage
fi
>&2 echo "user_type : ${user_type}"
>&2 echo "user_id : ${user_id} "
>&2 echo "country : ${country}"
>&2 echo "dev_env : ${dev_env}"
>&2 echo "position_id : ${position_id}"
>&2 echo "$# parameter/s remaining: $@"
>&2 echo "Looping through remaining parameter/s:"
# set input field separator to keep quoted parameters together
# for example, "my input" will remain as one input
IFS=$'\n'
for param in $@; do
>&2 echo -e "\t${param}"
done
echo "user ${user_type} with user id ${user_id} has been created with position_id $position_id"
exit 0
并在终端上尝试运行它:
bash test_bash --user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf
我收到的帮助信息如下:
[--user_type abc --user_id a1b2 --country aud --dev_env uat --position_id aFWf] passed to script
getopt creates [ --user_type 'abc' --user_id 'a1b2' --country 'aus' --dev_env 'uat' --position_id 'aFWf' --]
Usage: test_bash]
[ -a | --user_type input
[ -b | --user_id input ]
[ -c | --country input ]
[ -d | --dev_env input ]
[ -e | --position_id input ]
我尝试更新/更改一些东西,比如 args=getopt 和其他几个选项。但我的参数没有被脚本解析。提前感谢您的帮助。谢谢。