[This is my own study notes, welcome reprint, but please specify the source:http://blog.csdn.net/jesson20121020]
see how to pass parameters to a shell script today, you need to master two commands, one is the shift command, the other is getopts.
Script parameter Passingshift Command
Usage:
Shift n Shifts the parameter position to the left n bits at a time
If we want to implement the statistics of the total number of files, we can use this shift command, as follows:
opt2.sh
#!/bin/bash#op2 static files Total Lines;staticlines () { echo "static: ' basename ' filenames" exit} totalline=0if [$#-lt 2]then staticlinesfiwhile [$#-ne 0]do line= ' cat $ | wc-l ' echo ' $1:${line} ' t otalline=$[$totalline + $line] shiftdoneecho "-------------------------------------" echo "totalline:${ Totalline} "
Give executable permission to execute:
[Email protected]:~/develop/worksapce/shell_workspace$ chmod a+rx opt2.sh [email protected]:~/develop/worksapce/ shell_workspace$./opt2.sh static:opt2.sh filenames[email protected]:~/develop/worksapce/shell_workspace$./opt2.sh lsout.txtstatic:opt2.sh filenames[email protected]:~/develop/worksapce/shell_workspace$./opt2.sh lsout.txt Name.txt lsout.txt:18name.txt:4-------------------------------------Totalline:22[email protected]:~/develop/ worksapce/shell_workspace$./opt2.sh lsout.txt name.txt while_test1.sh lsout.txt:18name.txt:4while_test1.sh:6------ -------------------------------totalline:28
With the shift command, we can easily implement information such as statistics log.
getopts Command
The command can obtain multiple command-line arguments.
or a script to analyze the use of getopts
optsget.sh
#!/bin/bash#optsgetall=falsehelp=falsefile=falseverbose=falsewhile getopts Ahfvc:optiondo case $OPTION in A) all=true echo "All are $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 $-[a H F v]-[c value]" ;; Esacdone
Given executable permissions, the execution results are as follows:
[Email protected]:~/develop/worksapce/shell_workspace$./optsget.sh-aall is True[email protected]:~/develop/ worksapce/shell_workspace$./optsget.sh-a-fall is Truefile is True[email Protected]:~/develop/worksapce/shell_ workspace$./optsget.sh-a-f-hall is Truefile is Truehelp true[email ./optsget.sh-a-f-h-vall are Truefile is Truehelp trueverbose kspace$./optsget.sh-a-f-call is Truefile is true./optsget.sh: option requires one parameter--coptsget.sh-[a H F v]-[c Value][email Prot ected]:~/develop/worksapce/shell_workspace$./optsget.sh-a-f-c Jessonall is Truefile TRUEC
It is not difficult to see that multiple parameters can be obtained through the getopts command, and you can also specify a value for each parameter and add: If you need to specify a value.
Shell script for Linux learning-------script parameter passing