第七章.脚本参数的传递
shift命令
shift n 每次将参数位置向左偏移n
1#!/bin/bash
2#opt2
3usage()
4{
5echo "usage:`basename $0` filename"
6}
7totalline=0
8if [ $# -lt 2 ];then
9 usage
10fi
11while [$# -ne 0]
12do
13 line=`cat $1|wc -l`
14 echo "$1 : ${line}"
15 totalline=$[$totalline+$line]
16 shift # $# -1
17done
18echo "-----"
19echo "total:${totalline}"
20
21// 输出
22[test@szbirdora 1]$ sh opt2.sh myfile df.out
23myfile : 10
24df.out : 4
25-----
26total:14
getopts命令
获得多个命令行参数 getopts ahfvc OPTION
–从ahfvc一个一个读出赋值给OPTION.如果参数带有:则把变量赋值给:前的参数–:只能放在末尾。该命令可以做获得命令的参数
1#!/bin/bash
2#optgets
3ALL=false
4HELP=false
5FILE=false
6while getopts ahf OPTION
7do
8 case $OPTION in
9 a)
10 ALL=true
11 echo "ALL is $ALL"
12 ;;
13 h)
14 HELP=true
15 echo "HELP is $HELP"
16 ;;
17 f)
18 FILE=true
19 echo "FILE is $FILE"
20 ;;
21 ?)
22 echo "`basename $0` -[a h f] file"
23 ;;
24 esac
25done
26[test@szbirdora 1]$ sh optgets.sh -a -h -m
27ALL is true
28HELP is true
29optgets.sh: illegal option -- m
30optgets.sh -[a h f] file
31getopts表达式:
32while getopts p1p2p3... var do
33 case var in
34 ..)
35 ....
36 esac
37done
- 如果在参数后面还需要跟自己的参数,则需要在参数后加:
- 如果在参数前面加:表示不想将错误输出
getopts函数自带两个跟踪参数的变量:optind,optarg
- optind初始值为1,在optgets处理完一次命令行参数后加1
- optarg包含合法参数的值,即带:的参数后跟的参数值
至此,基础部分先告一段落,接下来我会继续发行shell的高级编程部分。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
- Link: https://blog.361way.com/relay/234.html
- License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.