Shell 中 getopts 示例用法

    • 1、用法
    • 2、示例

1、用法

getopts 可以获取用户在命令下的参数,然后根据参数进行不同的提示或者不同的执行。

它的用法是:

getopts option_string variable

getopts一共有两个参数, option_string 是类似于-a这样的选项,variable 是 hello这样的参数。

各个选项之间可以通过冒号 : 进行分隔,也可以直接相连接, 表示选项后面必须带有参数,如果没有可以不加实际值进行传递。
也就是说后面没有接 的可以不带参数,也可以带参数;而带有 必须带参数,否则会报错 (此时可以在改选项前面添加 ,在没有添加参数时就不会报错了)。

2、示例

[root@yanta test] # cat opt_test.sh
#!/bin/bash
# Name: /home/yanta/test/opt_test.sh
# Author: Yanta
# Dsc: Test use of  

Usage(){
    echo "USAGE: /bin/bash /home/yanta/test/opt_test.sh < -a LowerName > < -h >"
}

Test(){
    while getopts "a:h" opt
    do
        case $opt in
        a)
        echo "My LowerName is $OPTARG"
        ;;
        h)
        Usage
        ;;
        esac
    done    
}

main(){
    [ $# -lt 1 ] && {
        Usage
        exit -1
    }
    Test $*
}

main $*

运行结果:

[root@yanta test] # ./opt_test.sh
USAGE: /bin/bash /home/yanta/test/opt_test.sh < -a LowerName > < -h >
[root@yanta test] # ./opt_test.sh -h
USAGE: /bin/bash /home/yanta/test/opt_test.sh < -a LowerName > < -h >
[root@yanta test] # ./opt_test.sh -h help 
USAGE: /bin/bash /home/yanta/test/opt_test.sh < -a LowerName > < -h >
[root@yanta test] # ./opt_test.sh -a yanta
My LowerName is yanta
[root@yanta test] # ./opt_test.sh -a  # 选项后接有 : 时, 不添加第二个参数会报错
./opt_test.sh: option requires an argument -- a

你可能感兴趣的:(Shell)