HOME 生活记录运维/编程
作者/来源:yixinu.com
栏目:运维/编程
日期:2012-04-07 15:22:29

getopts 用来检测命令行中传递给脚本的有效参数

example1:复制文件到指定位置


#!/bin/bash
src=/etc/ssh.conf
dest=/tmp
if [ "$1" == "-h" ]; then
        echo -e "-s --sourcettsource file"
fi

while getopts s:d: OPT
do
        case $OPT in
                s) src=$OPTARG;;
                d) dest=$OPTARG;;
                ?)  echo "Usage:";;
        esac
done
echo "copy $src --> $dest"


example2:

#!/bin/bash

NO_ARGS=0
E_OPTERROR=65

if [ $# -eq $NO_ARGS  ]
then
        echo "Usage:`basename $0` options(-mnopqrs)"
fi

while getopts mnopq:rs Option
do
    case $Option in
      m) echo "This is m";;
      n) echo "This is n";;
      o) echo "This is o";;
      p) echo "This is p";;
      q) echo "This is q:$OPTARG";;
      r) echo "This is r";;
      s) echo "This is s";;
      *) echo "This default";;
    esac
done

分享到:

Copyright © 2013-2014 yixinu.com 湘ICP备14004402号

QQ:316686606  Email: 316686606@qq.com