zoukankan      html  css  js  c++  java
  • 向脚本传递参数

    1.使用$#

    $ pg opt.sh

    #!/bin/sh
    #opt.sh

    usage()
    {
        echo "usage:'basename $0' start|stop process name "
    }
    OPT=$1
    PROCESSID=$1
    if [ $# -ne 2 ]
    then
        usage
        exit 1
    fi
    case $OPT in
    start|Start) echo "Starting..$PROCESSID"
      ;;
    stop|Stop) echo "Stopping...$PROCESSID"
      ;;
    *) usage
      ;;
    esac

    $# 表示命令行的个数,执行时用

    $ opt.sh start named

    Starting..start

    $ opt.sh start

    usage:'basename /home/dongjichao/bin/opt.sh' start|stop process name

    2.shift命令

    shift可以从左至右的选择命令行参数,如

    $ cat -n opt2.sh
         1    #!/bin/sh
         2    # opt2.sh
         3    loop=0
         4    while [ $# -ne 0 ]
         5    do
         6        echo $1
         7        shift
         8    done

    $ history | tail -n 10
     1541  cat opt
     1542  cat opt.sh
     1543  opt.sh start named
     1544  opt.sh start
     1545  cat -n opt2.sh
     1546  history | tail 100
     1547  history | tail -n 100
     1548  opt2.sh file1 file2 file3
     1549  history | tail -n 30
     1550  history | tail -n 10
    dongjichao@dongjichao:~/bin$ !1548
    opt2.sh file1 file2 file3
    file1
    file2
    file3

    3.使用shift处理文件转换

    $ cat opt3.sh
    #!/bin/sh
    #opt3.sh

    usage()
    {
        echo "usage:`basename $0` -[l|u] file [files] ">&2
        exit 1
    }

    if [ $# -eq 0 ]; then
        usage
    fi

    while [ $# -gt 0 ]
    do
        case $1 in
            -u|-U) echo "-u option specified"
                shift
                ;;
            -l|-L) echo "-l option specifed"
                shift
                ;;
            *) usage
                  ;;
        esac
    done

    运行

    $ opt3.sh -u -l -k
    -u option specified
    -l option specifed
    usage:opt3.sh -[l|u] file [files]

    4.getopts

    有时需要写类似  $ 命令 -l -c 23这样的命令,这时需要用到getopts

    以下getopts脚本接受下列选项或参数

    a  设置变量ALL为true

    h  设置变量HELP为true

    f  设置变量FILE为true

    v  设置变量VERBOSE为true

    $ cat getopt1.sh

    #!/bin/sh
    #getopt1

    ALL=false
    HELP=false
    FILE=false
    VERBOSE=false

    while getopts ahfgv OPTION
    do
        case $OPTION in
        a)ALL=true
          echo "ALL is $ALL"
          ;;
        h)HELP=true
          echo "HELP is $HELP"
          ;;
        f)FILE=true
          echo "FILE is $FILE"
          ;;
        v)VERBOSE=true
          echo "VERBOSE is $VERBOSE"
          ;;
        esac
    done

    运行上面的脚本

    $ getopt1.sh -a -h  

    ALL is true
    HELP is true

  • 相关阅读:
    sass教程汇总
    SASS用法指南
    SASS、COMPASS 安装指南
    web前端开发分享-css,js进阶篇
    更强的微光闪烁效果--第三方开源--Shimmer-android
    QQ分组实现,可收缩---ExpandableListView
    FaceBook微光闪烁---第三方开源--shimmer-android
    在xml中添加array
    一个ListView中显示不同的item(分组)
    在xml中调用自己用java代码定义的View
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2053615.html
Copyright © 2011-2022 走看看