操作系统

使用getopts获取命令行参数
作者 ruiqingzheng 2006年01月18日 09:33

    常用的参数

    $# 参数的个数

    $* 所有的参数

    $@ 所有的参数

    shift来处理参数 一般两种形式

    ============================

    while [ -n $# ]

    do

     :

     shift

    done

    =============================

    while [ $1 ]

    do

     :

     shift n

    done

    ==============================

    使用getopts来取参数

    getopts string options

    例如

    while getopts "lur:" opt

    do

     case $opt in

     l) list="menu";;

     u) user="$OPTARG";;

     r) ro="$OPTARG";;

     ?) echo "Usage: `basename $0` -l -u user -r yes|no";;

     esac

    done

    # 说明

    while getopts "lur:" opt

    string 部分 "lur" 指定可以带的参数为 -l -u -r 并保存在opt这个变量中 ,

    r后面的冒号表示 -r 后面必须指定一个参数 比如 -r yes

    并且这个参数yes默认是保存在OPTARG变量中的

    如果 -r 后面没有指定参数 那么会提示出错 并opt被设置为?重新处理 这个opt

    对于必须制定参数 却没有读取到的错误 可以在string的开始加上: 来处理

    修改后

    #!/bin/bash

    while getopts ":lu:r:" opt

    do

     case $opt in

     l) list="menu";;

     u) user="$OPTARG";;

     r) ro="$OPTARG";;

     ?) echo "Usage: `basename $0` -l -u user -r yes|no";;

     esac

    done

    运行一下

    [root@localhost code]# ./sc.sh -l -u

    Usage: sc.sh -l -u user -r yes|no

    [root@localhost code]# ./sc.sh -u -r -l

    [root@localhost code]#

    ./sc.sh -u -r -l 没有出错 这时

    

    

    

    

    

    本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/9293/showart_68892.html

打开APP阅读全文

使用getopts获取命令行参数

使用getopts获取命令行参数

长按识别二维码 进入IT168查看全文

请长按保存图片
{{data.thematic.text}}

相关文章

加载中...

分享到

请使用浏览器的分享功能
分享到微信等