gpt4 book ai didi

linux - 如何验证传递的参数、值以及参数之间的依赖关系?

转载 作者:太空宇宙 更新时间:2023-11-04 04:43:22 24 4
gpt4 key购买 nike

我对 shell 脚本非常陌生,我正在编写一个脚本,需要用户提供一些参数。这些参数的描述在帮助部分给出。我想验证用户传递的这些参数,以便他不会传递错误的参数。某些参数需要采用特定格式,例如日期时间。 -

    #!/bin/bash
set -u
set -o pipefail

exit_status=0
FRUIT=fruit
CERT_PATH=cert
KEY_PATH=key
USERNAME=username
DATETIME=datetime

die() {
printf '%s\n' "$1" >&2
exit 1
}

show_help() {
cat << EOF


HELP:
==========================================================================================================================

Description:

--fruit or -f: fruit name: mango, strawberry, grapes, apple, kiwiXX
--cert or -c cert
--key or -k key
--username or -un username to be passed when fruit is apple
--datetime or -dt datetime format: 2018-11-07 10:02:01

--help or -h: help for <cmd>

==========================================================================================================================

EOF
exit "$exit_status"
}

set_arguments () {
while [ $# != 0 ]; do

case "${1:-}" in
-h|-\?|--help)
show_help # Display a usage synopsis.
exit
;;
-f|--fruit)
FRUIT="${2:-}"
shift
;;
-c|--cert)
CERT_PATH="${2:-}"
shift
;;
-k|--key)
KEY_PATH="${2:-}"
shift
;;
-un|--username)
USERNAME="${2:-}"
shift
;;
-dt|--datetime)
DATETIME="${2:-}"
fi
shift
;;
-?*)
show_help
exit 1
;;
*)
die 'ERROR: unknown argument.'
;;
esac
shift
done
}

# get the incoming arguments and set the variables.
set_arguments "$@"

参数 --fruit 不能是 mango, strawberry, grapes, apple, or kiwi-qx-XX 以外的任何内容。如果是kiwi ,它必须包含 -qx- and a number 。例如:kiwi-qx-01kiwi-qx-02kiwi-qx-100 。如果水果是苹果,用户必须传递参数用户名。如果不是苹果,则用户不得传递用户名。日期时间应具有特定格式,如帮助部分所示。如何验证这些传递的参数?最好的方法是什么?

最佳答案

我知道严格来说这不是验证,但您可以简单地对特定参数输入执行以下操作:

case "$1" in
valueneeded)
#do something
;;

*)
clear
explain what the accepted input is
exit 1
esac

至于值(value)观:

这取决于所讨论的值。例如:为了检查该值是否是一个 url:

regexdom='(https?|http|)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
if ! [[ $1 =~ $regexdom ]]
then
echo "Url introduced is invalid exiting srcipt..."
exit 1
fi

将 regexdom 替换为您需要完成的正则表达式。您可以使用https://regex101.com/现场测试脚本中之前的正则表达式实现。

此外,查看可能的参数数量,也许最好考虑切换到 getopts:

while getopts ":a" opt; do
case $opt in
a)
echo "-a was triggered!" >&2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
;;
esac
done

希望这有帮助

关于linux - 如何验证传递的参数、值以及参数之间的依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53543716/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com