首页 > 代码库 > linux学习之shell脚本 ------- 脚本参数传递

linux学习之shell脚本 ------- 脚本参数传递

[本文是自己学习所做笔记,欢迎转载,但请注明出处:http://blog.csdn.net/jesson20121020]

今天再来看一下如何向shell脚本传递参数,需要掌握两个命令,一个是 shift命令,另一个是getopts。

脚本参数传递

  shift命令

   用法:

    shift n 每次将参数位置向左偏移n位

   假如我们要实现统计多个文件的总行数,就可以用到这个shift命令了,如下:

opt2.sh

#!/bin/bash
#op2  static files total lines;
staticlines(){
   echo "static:`basename $0` filenames"
   exit
}
totalline=0
if [ $# -lt 2 ]
then
    staticlines
fi
while [ $# -ne 0 ]
do
    line=`cat $1 | wc -l`
    echo "$1:${line}"
    totalline=$[ $totalline+$line ]
    shift
done
echo "-------------------------------------"
echo "totalline:${totalline}"
   给予可执行权限,执行:

jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ chmod a+rx opt2.sh 
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./opt2.sh 
static:opt2.sh filenames
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txt
static:opt2.sh filenames
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txt name.txt 
lsout.txt:18
name.txt:4
-------------------------------------
totalline:22
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./opt2.sh lsout.txt name.txt while_test1.sh 
lsout.txt:18
name.txt:4
while_test1.sh:6
-------------------------------------
totalline:28
   通过shift 命令,我们可以很容易地实现统计log等信息。

  getopts命令

   该命令可以获得多个命令行参数。

   还是一个脚本来分析getopts的用法

optsget.sh

#!/bin/bash
#optsget
ALL=false
HELP=false
FILE=false
VERBOSE=false
while getopts ahfvc: 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"
         ;;
     c)
         c=$OPTARG
         echo "c valuse is $c"
         ;;
     \?)
         echo "`basename $0` -[a h f v] -[c value]"
         ;;
      esac
done
   给予可执行权限,执行结果如下:

jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a
ALL is true
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f
ALL is true
FILE is true
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -h
ALL is true
FILE is true
HELP is true
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -h -v
ALL is true
FILE is true
HELP is true
VERBOSE is true
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -c
ALL is true
FILE is true
./optsget.sh: 选项需要一个参数 -- c
optsget.sh -[a h f v] -[c value]
jesson@jesson-K43SV:~/develop/worksapce/shell_workspace$ ./optsget.sh -a -f -c jesson
ALL is true
FILE is true
c valuse is jesson
  不难看出,可以通过getopts命令取得多个参数,而且还可以为每个参数指定值,在需要指定值的参数后加:即可。


linux学习之shell脚本 ------- 脚本参数传递