本文介绍了getopts的使用为标志和选项解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用我的剧本getopts的,我想工作,它选项解析以下的所有订单。

I am using getopts in my script and I want to work it for all the following order of option parsing.

./myscript -c server
./myscript -c -h server
./myscript server -c
./myscript -h server -c
./myscript server

我使用的MyScript如下:

I am using myscript as follows.

#!/bin/bash
while getopts c:h: var
do
case $var in 
h) host=$OPTARG;;
c) FLAG=1
esac
done

下面服务器是一个参数,应该载入甚至-h选项指定与否,也是我使用了FLAG.Is有没有办法-c选项来获得此实现。

Here "server" is a argument and should load even -h option specifies or not and also -c option I am using for a FLAG.Is there a way to get this achieved.

推荐答案

有时,最好不要使用 getopts的都:

Sometimes it's better not to use getopts at all:

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -c)
        FLAG=1
        ;;
    -h)
        HOST=$2
        shift
        ;;
    -*)
        echo "Unknown option: $1"
        exit 1
        ;;
    *)
        HOST=$1
        ;;
    esac
    shift
done

通过,因为你错过了两个分号脚本会给你一个语法错误方式:

By the way your script would give you a syntax error since you missed the two semicolons:

c) FLAG=1 ;;

这篇关于getopts的使用为标志和选项解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 17:48