开发者

In a bash script, can i use && to group two command line arguments together

开发者 https://www.devze.com 2023-03-14 18:11 出处:网络
Here is a snippet: for arg in \"$@\"; do if [ $arg == \"--coverage\" ]; then ENABLE_COVERAGE=1 shift elif [ $arg == \"--mysql\" ]; then

Here is a snippet:

for arg in "$@"; do
    if [ $arg == "--coverage" ]; then
        ENABLE_COVERAGE=1
        shift
    elif [ $arg == "--mysql" ]; then
        MYSQL_ONLY=1
        shift
    elif [ $arg == "--psql" ]; then
        PSQL_ONLY=1
        shift
    elif [ $arg == "-h" ] || [ $arg == "--help" ]; then
        usage
        shift
    elif [ $arg == "--qa" ]; then
        QA_ONLY=1
        PSQL_ONLY=1
        MYSQL_ONLY=1
        shift
   elif [ $arg == "--qa" ] && [ $arg == "--mysql" ]; then
        QA_ONLY=1
        MYSQL_ONLY=1
        shift
   elif [ $arg == "--qa" ] && [ $arg == "--psql" ]; then
        QA_ONLY=1
        PSQL_ONLY=1
        shift
    elif [ $arg == "--" ]; then
        shift 
        break          开发者_如何学C                                     
    fi                                                      
done                


$arg can never be equal to --qa and --mysql at the same time.

If you're talking about different arguments then yes, you can do something like this:

if [[ $arg1 == "--qa" && $arg2 == "--mysql" ]] ; then
    QA_ONLY=1
    MYSQL_ONLY=1
fi

But I often find it's a better idea to just scan the arguments sequentially setting a flag for each one, then using the flags to decide behaviour. Otherwise you're either limiting your command line arguments to a specific order (xyz --qa --mysql will work but xyz --mysql -- qa won't) or your code becomes hideously complicated since it's trying to check every argument against every possibility.


If you can call getopt in bash, you can't call getopt, it shouldn't use long option name. use getopts instead of getopt.(below is a example)

#!/bin/bash

while getopts qm OPT
do
  case $OPT in
    q) opt_qa=1;;
    m) opt_mysql=1;;
  esac
done

if [ $opt_qa = 1 ]; then
  # do as qa
fi

if [ $opt_mysql = 1 ]; then
  # do as mysql
fi
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号