"Option does not exist" 与 bash 案例陈述

"Option does not exist" with bash case statement

我正在尝试执行以下操作以向 bash 命令添加一个简单的开关。该标志用于打开一个选项,以使用另一个名为 'terminus'.

的程序执行一些文件备份任务

然而,当我 运行 我的脚本(命名为 prepmultidev.sh)是这样的:

bash prepmultidev.sh mysite.updatejan31 -b

当我在命令末尾添加 -b 选项时,它会显示“跳过备份”(即使它应该显示“正在备份 live/test/dev...”),然后我收到一条错误消息“'-b' 选项不存在”。当我不添加它时,它仍然说“跳过备份”(现在正确)但是 returns 和“没有足够的参数(缺少:'multidev')。”在一个接一个地阅读教程后,我使用的代码与其他人使用的代码相同,但我的不是,我仍然和刚开始时一样困惑。

#!/bin/bash
# Example: bash prepmultidev.sh mysite multidevname
# will back up live/test/dev and create a multidev of mysite.
# Add the -b flag if a backup of live/test/dev is required.
SITE=
MULTIDEV=
BACKUP=

# Exit on error
set -e

# Authenticate Terminus
terminus auth:login --machine-token=J6nCtWYtva8dtPk3xQ95ZJIG6FuSfQ6t14c0to-tmhH9R

# Check to see if a backup is needed of live/test/dev.

    case "$BACKUP" in
        b)
            echo "Backing up live/test/dev..."
            # Create backups of live, test, and dev environments
            terminus backup:create $SITE.live & 
            terminus backup:create $SITE.test &
            terminus backup:create $SITE.dev &
            ;;
        *) 
            echo "Skipping backup"
            ;;
    esac

# Now do some other stuff with $SITE.$MULTIDEV

我缺少什么才能让它在 -b 标志存在时识别它并进行备份,或者在它不存在时简单地回显“跳过备份”?

bash case 语句要求您指定一个模式,但如果您不指定任何 pattern matching syntax,它只会匹配整个字符串。在您的示例中,b) 将匹配 b,但不会匹配 -b

要解决您眼前的问题,您还可以在案例模式中指定 - 以使其匹配:

    case "$BACKUP" in
        -b)
            echo "Backing up live/test/dev..."
            # Create backups of live, test, and dev environments
            terminus backup:create $SITE.live & 
            terminus backup:create $SITE.test &
            terminus backup:create $SITE.dev &
            ;;
        *) 
            echo "Skipping backup"
            ;;
    esac

如果你想添加更多的标志,你可能会更好地使用 getopts or the more flexible GNU getopt 如果你可以使用它(不要与 BSD 或 POSIX getopt 混淆,这是更有限的)。