gpt4 book ai didi

bash - Bash 的命令行参数验证库

转载 作者:行者123 更新时间:2023-11-29 09:04:44 25 4
gpt4 key购买 nike

我正在寻找为 bash 执行命令行参数验证的可重用代码片段。

理想情况下类似于 Apache Commons CLI 提供的功能:

Commons CLI 支持不同类型的选项:

  • 类似 POSIX 的选项(即 tar -zxvf foo.tar.gz)
  • GNU 喜欢长选项(即 du --human-readable --max-depth=1)
  • 带有附加值的短选项(即 gcc -O2 foo.c)
  • 带有单个连字符的长选项(即 ant -projecthelp)
  • ...

它会自动为程序生成一条“使用情况”消息,如下所示:

usage: ls
-A,--almost-all do not list implied . and ..
-a,--all do not hide entries starting with .
-B,--ignore-backups do not list implied entried ending with ~
-b,--escape print octal escapes for nongraphic characters
--block-size <SIZE> use SIZE-byte blocks
-c with -lt: sort by, and show, ctime (time of last
modification of file status information) with
-l:show ctime and sort by name otherwise: sort
by ctime
-C list entries by columns

我会将此代码片段包含在我的 Bash 脚本的开头,并在脚本中重复使用它。

一定有这样的东西。我不相信我们都在为此效果或类似效果编写代码:

#!/bin/bash

NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS=3

number_of_supplied_command_line_arguments=$#

function show_command_usage() {
echo usage:
(...)
}

if (( number_of_supplied_command_line_arguments < NUMBER_OF_REQUIRED_COMMAND_LINE_ARGUMENTS )); then
show_command_usage
exit
fi

...

最佳答案

这是我使用的解决方案(在某个地方的网上找到的,可能是这里本身,不太记得了)。请注意 GNU getopt ( /usr/bin/getopt ) 确实支持使用选项 ant -projecthelp 的单破折号长选项 ( -a 样式) ,但是我没有使用它,所以它没有显示在示例中。

此代码解析 3 个选项:--host value-h value , --port value-p value--table value-t value .如果未设置所需参数,则对其进行测试

# Get and parse options using /usr/bin/getopt
OPTIONS=$(getopt -o h:p:t: --long host:,port:,table: -n "$0" -- "$@")
# Note the quotes around `$OPTIONS': they are essential for handling spaces in
# option values!
eval set -- "$OPTIONS"

while true ; do
case "$1" in
-h|--host) HOST=$2 ; shift 2 ;;
-t|--table)TABLE=$2 ; shift 2 ;;
-p|--port)
case "$2" in
"") PORT=1313; shift 2 ;;
*) PORT=$2; shift 2 ;;
esac;;
--) shift ; break ;;
*) echo "Internal error!" ; exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if

使用 getopts 的替代实现shell内置(这只支持小选项):

while getopts ":h:p:t:" option; do
case "$option" in
h) HOST=$OPTARG ;;
p) PORT=$OPTARG ;;
t) TABLE=$OPTARG ;;
*) usage(); exit 1 ;;
esac
done
if [[ -z "$HOST" ]] || [[-z "$TABLE" ]] || [[ -z "$PORT" ]] ; then
usage()
exit
if

shift $((OPTIND - 1))

进一步阅读 GNU getoptgetopts bash builtin

关于bash - Bash 的命令行参数验证库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11220715/

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