【问题标题】:Is it possible to mix getops with optional positional parameters?是否可以将 getops 与可选的位置参数混合使用?
【发布时间】:2021-11-26 02:25:57
【问题描述】:

我编写了一个脚本来自动重新启动我的网络服务器,进行某些检查,然后将带有时间戳的消息打印到日志文件中。因为我从不同的地方调用这个文件(cron 作业,当我更新我的站点时,手动等等),我想有一种方法可以根据我调用它的原因将不同的消息打印到日志文件中。我决定使用选项来执行此操作,并且还决定添加帮助、详细和测试选项。

选项部分的代码:

# initializing variables
test=false
help=false
verbose=false
modeCount=0
msg="restarted"

# looking at options
while getopts ":aeghmstv" option; do
    case $option in
        a) # Automatic restart
            ((modeCount+=1))
            msg="$msg automatically";;
        e) # Error-triggered restart
            ((modeCount+=1))
            msg="$msg due to an error";;
        g) # Pull-triggered restart
            ((modeCount+=1))
            msg="$msg on git pull";;
        h) # Help
            help=true;;
        m) # Manual restart
            ((modeCount+=1))
            msg="$msg manually";;
        s) # Startup-triggered restart
            ((modeCount+=1))
            msg="$msg on startup";;
        t) # Testing mode
            test=true;;
        v) # Verbose mode
            verbose=true;;
       \?) # Invalid option
            echo "Error: Invalid option; use the h option for help"
            exit;;
    esac
done

# checking for input errors
if [ "$help" == true ]; then
    if [ $modeCount -gt 0 ] || [ "$test" == true ] || [ "$verbose" == true ]; then
        echo "Error: No other options can be used with h; use the h option for help"
    else
        help
    fi
    exit
fi
if [ $modeCount != 1 ]; then
    echo "Error: 1 log message option must be used; use the h option for help"
    exit
fi

但是,另外,我希望能够将字符串作为位置参数传递,以便将其他信息添加到我的日志文件中。 例如,如果我运行:

./restart.sh -a

它记录如下内容:

2021-10-04T00:00:04 restarted automatically

但我希望能够更改它以便我可以(可选)运行:

./restart.sh -a "daily restart"

它会改为记录:

2021-10-04T00:00:04 restarted automatically: daily restart

我发现 this question 关于混合 getops 和参数,但如果我希望参数是可选的,我不知道该怎么做。

一旦我得到那个字符串,就很容易简单地添加如下一行:

msg="$msg: $info"

但我不确定如何验证这样的参数是否存在,然后将其存储在变量中。

PS:无论参数/选项的顺序如何,我也希望它能够工作。例如,我想要:

./restart.sh -a "daily restart"

and

./restart.sh "daily restart" -a

以同样的方式工作。

【问题讨论】:

  • getopts 完成后,位置参数都是其后的非选项参数。

标签: bash shell parameters options


【解决方案1】:

您可以编写自己的 if/else 来解析第二个参数。它会解决你的问题,但我不推荐这种方式。 无论如何,请尝试:

#!/bin/bash

而 getopts ":aeghmstv" 选项;做 案例$选项在 a) # 自动重启 ((modeCount+=1)) 如果 [ ! "${2:0:1}" == "-" ];然后 味精="$2" 转移 别的 味精=“自动” 菲;; 经社理事会 回声“味精:$味精” 完成

【讨论】:

  • 我考虑过使用 $OPTARG,但由于我有 5 个不同的选项(a、e、g、m、s)我想让它们能够使用附加参数,所以我必须添加额外的 5 个选项(这对我来说似乎太多了)。我特别想知道是否有某种方法可以使用与选项分开的 1 个可选参数。就像他们在链接问题中的做法一样,除了参数是可选的。我还希望它与订单无关,这需要对所有内容都有一个非常具体的订单。
  • 在这种情况下,您可以使用自己的循环解析参数并尝试解析以破折号开头的附加参数。
  • 我已经通过手动检查下一个参数的示例更新了我的答案。如果适合您,请尝试
猜你喜欢
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-18
  • 1970-01-01
  • 2010-12-31
  • 1970-01-01
  • 2017-06-30
相关资源
最近更新 更多