向脚本传递参数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值