在bash脚本中获取require和optional参数

问题描述 投票:0回答:1

抱歉我的新手问题,我很困惑!

我想出于某些原因制作一个bash脚本。我需要在运行脚本时传递一些参数。

例如:

script.sh build --with-test --without-test2 --with-test3
script.sh config
script.sh config --with-test3 --without-test2
script.sh config --add this is a test

buildconfig是必需的,其他参数也是可选的,使用参数的顺序并不重要。

我写了这段代码:

if [[ $# -lt 1 ]]; then
    printf "build or config parameter is missing"
    exit;
fi

while [[ $# -gt 0 ]]
do
key="$1"
    case $key in
        build )
            mode=1
            shift
            shift
            ;;
        config )
            mode=0
            shift
            shift
            ;;
        -wt2 | --without-test2 )
            wt2=0
            shift
            shift
            ;;
        -wt3 | --with-test3 )
            wt3=1
            shift
            shift
            ;;
        -wt0 | --with-test )
            wt0=1
            shift
            shift
            ;;
        -add | --additional )
            additional_command=$2
            shift
            shift
            ;;
        -h | --help )
            help
            shift
            shift
            exit
            ;;
        *)
            echo "Missing parameter."
            shift
            shift
            exit
            ;;
    esac
done

但是我的代码不能正常工作,即使没有buildconfig,脚本也会运行,我无法弄清楚如何编写if语句

bash
1个回答
0
投票

使用两次换班是一个错误。您可以通过检查mode的值来确认已指定config AND / OR build。其他命令也存在问题。

考虑移动shift语句。

我已经为你的程序添加了一些调试,看看结果是什么:

$ script.sh  --with-test --without-test2 --with-test3
additional_command=
mode=
wt0=1
wt2=
wt3=1

如您所见,即使指定了--with-test2,也未设置wt2。

以下是如何解决问题的方法:

  • 移除案件中的班次(特殊处理除外)
  • 查看mode参数以查看是否已设置(test -z)

代码如下:

#!/bin/bash

if [[ $# -lt 1 ]]; then
    printf "build or config parameter is missing"
    exit;
fi

while [[ $# -gt 0 ]]
do
key="$1"
shift
    case $key in
        build )
            mode=1
            ;;
        config )
            mode=0
            ;;
        -wt2 | --without-test2 )
            wt2=0
            ;;
        -wt3 | --with-test3 )
            wt3=1
            ;;
        -wt0 | --with-test )
            wt0=1
            ;;
        -add | --additional )
            # Get the rest of the parameters, right?
            additional_command=$*
            shift $# # Shift to "deplete" the rest of the params
            ;;
        -h | --help )
            help
            # No need to shift if you are exiting
            exit
            ;;
        *)
            echo "Missing parameter."
            # No need to shift if you are exiting
            exit
            ;;
    esac
done

#Here's a little debug code that you can remove or just comment out with : 
#Change first line to : cat <<EOF if you want to comment out.

cat <<EOF
    additional_command=$additional_command
    mode=$mode
    wt0=$wt0
    wt2=$wt2
    wt3=$wt3
EOF

if [ -z "$mode" ] ; then
  echo "Missing config or build parameter"

fi
© www.soinside.com 2019 - 2024. All rights reserved.