Chapter 2: handling user input
Command Line Parameters
Read Parameters
BASH Shell assigns some special variables called positional parameter to all the parameters entered by the command line.
Even include the program name
$0: Program name (Absolute program path),You can use the basename function (basename $0) for $0), It only returns the program name
$ I (9> I> 0): Parameter I
If you need more than 9 parameters, you only need $ {10}In this way, you can
If the script requires parameters but no parameters are input during execution, an error is returned during execution.
if [ -n "$1" ]……
Check whether there are parameters before processing.
Special parameter variables
$ #: Parameter quantity
$ {! #}: The last parameter.Dollar signs ($) are not allowed in curly braces),The exclamation point (!) is used here (!)
The following code is incorrect.
#!/bin/bashecho We have "$#" "parameter(s)"echo The last parameter is "${$#}" # wrong wayecho The last parameter is "${!#}" # right way
Execution result:
$ param_test 1 1 1 5We have 4 parameter(s)The last parameter is 1535The last parameter is 5
Note: When the command line does not have any parameters, $ # returns 0, while $ {! #} Return function name
Extract all parameters on the command line
$ *:Save all parameters provided on the command line as one word
$ @:Set of all parameters
#! /Bin/bashecho "\ $ * And \ $ @ test" Echo "\ $ * is:" $ * # Here the two output results are the same echo "\ $ @ is: "$ @ # Count = 0for VaR in" $ * "do count = $ [$ count + 1] echo" $ count: "$ vardoneecho" \ $ * done. "Count = 0for VaR in" $ @ "do count = $ [$ count + 1] echo" $ count: "$ vardoneecho" \ $ @ done."
Output result:
$* and $@ test$* is:a b c$@ is:a b c1:a b c$* done.1:a2:b3:c$@ done.
Mobile Data
Shift
Place each variable one in advance, $0 remains unchanged, and $1 is removed.
count=1while [ -n "$1" ]do echo "Paramter #$count=$1" count=$[$count + 1] shiftdone
Note: After the parameter is removed, it cannot be restored.
Processing options
while [-n $1 ]do case "$1" in -a) echo "Found the -a option" ;; -b) echo "Found the -b option" ;; *) echo "$1 is not a option" ;; esac shiftdone
Separate parameters and options
In Linux, the double broken line (--) indicates that the option ends.
#! /Bin/bashwhile [-n "$1"] Do case "$1" in-a) echo "found option A";-B) echo "found option B"; --) shift break; # Jump out of while instead of case *) echo "$1 not a option ";; esac shiftdonefor P in $ @ Do echo "$ P is a Param. "Done
Process option with value
#! /Bin/bashwhile [-n "$1"] Do case "$1" in-a) echo "option A";-B) echo "option B. $2 is a Param. "# If option B is found, $2 should be the value shift of Option B; # p281 page. The original text is shift 2, which is not required, because there is no break output loop --) shift break;-C) echo "option C"; *) echo "$1 is not a option. "; esac shiftdone
Getopt
Syntax:
Getopt
Options optstring ParametersIn
OptstringAll options are listed. The value option must be followed by a colon (:). If the parameter contains an invalid parameter, an error message is displayed.
$ getopt ab:cd -a -b pb -cde p1 p2getopt: invalid option -- 'e' -a -b pb -c -d -- p1 p2
-Q: Blocking error reports
$ getopt -q ab:cd -a -b pb -cde p1 p2 -a -b 'pb' -c -d -- 'p1' 'p2'
Set -- command: Set replaces the command line parameter with the value of the SET command line.Set -- 'getopt AB: cd "$ @"'After formatting the parameters in getopt, replace the original parameters in the command line with set. Save the following script to the getopt_test file.
#!/bin/bashset -- `getopt a:b:c "$@"`echo "param = $@"while [ -n "$1" ]do case "$1" in -a) echo "found option a and param = $2" shift ;; -b) echo "found option b and param = $2" shift ;; -c) echo "found option c, no param." ;; --) ;; *) echo "what's this?" break ;; esac shiftdone
The running result is as follows:
$ getopt_test -a test -b test -egetopt: invalid option -- 'e'param = -a test -b test --found option a and param = testfound option b and param = test
As you can see,
Getopt can identify unknown optionsHowever, it still has some shortcomings.
The following is an example of incorrect options.
$ getopt_test -a -b -cparam = -a -b -c --found option a and param = -bfound option c, no param.
Here,-B is recognized as the-a parameter. Of course, this is caused by incorrect user input. However, getopt is not correctly identified.
Let's look at another example with spaces in the parameter.
$ getopt_test -a "x y"param = -a x y --found option a and param = xwhat's this?
Apparently, getopt treats "x y" as two parameters/options.The last problem can be solved using the following command:
Getopts
Syntax:
Getopts
Optstring variable
Two environment variables used by getopts
Optarg: if the option needs to be followed by a parameter value, this variable will save this parameter value.
Optind: location where the getopts parameter is being processed is saved
Note: To shield error messages, you must add a colon Before optstring, instead of using-Q
Getopts saves the current parameter as defined in the command lineVariableMedium
Each time getopts is called, it only processes one parameter in the command line. After all parameters are processed, it exits and returns an exit status code greater than 0.
#!/bin/bashwhile getopts abc:d optdo case $opt in a) echo "option -a found";; b) echo "option -b found";; c) echo "option -c found and param = $OPTARG";; d) echo "option -d found";; ?) p=$[$OPTIND-1] echo "what's this? "${!p} echo "what's this? "$opt;; esacdone
Unlike getopt, getopts automatically removes "-", so do not add "-" in case.Output result
$ param_test -a -b -c "a param" -d -eoption -a foundoption -b foundoption -c found and param = a paramoption -d found./param_test: illegal option -- ewhat's this? -ewhat's this? ?
Getopts outputs all unknown options with question marks, so we will see one more question mark in the last line.
Standardize optionsBelow are some common meanings of the options in the command (the original text is general, but not very general)
Option |
Description |
- |
Show all objects |
-C |
Generate a count |
-D |
Specify a directory |
-E |
Expand an object |
-F |
Specifies the file to read data. |
-H |
Display Command help information |
-I |
Ignore text case sensitivity |
-L |
Generate a long-format version of the output |
-N |
Use non-interactive mode (Batch) |
-O |
Specifies the output file to which all outputs are redirected. |
-Q |
Run in quiet mode |
-R |
Recursively process directories and files |
-S |
Run in quiet mode |
-V |
Generate detailed output |
-X |
Exclude an object |
-Y |
Yes for all questions |
Obtain user inputRead: receives input from a standard input (keyboard) or another file descriptor. After receiving the input, the READ command will put the data into a standard variable.
#!/bin/bashecho -n "Enter your name:"read nameecho "Hello $name"read -p "Enter your age:" ageecho "You are $age years old..."
The-N option of ECHO removes the line break at the end.-P:You can specify the prompt statement.You can save the input to multiple variables. If the variables in the variable table are not enough, the subsequent input will be saved to the last variable.
read -p "What would you like to eat?" f1 f2echo "you would like to eat $f1 and $f2"
If no variable is specified for read, The read content is saved to the reply environment variable.-T: Specifies the timeout time, in seconds.After timeout, read returns a non-0 exit status code.
#!/bin/bashread -n1 -p "Are you a boy?" answerechocase $answer iny|Y) echo "Oh, you're a boy.";;N|n) echo "Oh, you are not a boy.";;esac
-NNumber:When the number of characters is entered, read ends and the result is assigned to the variable.In the preceding example, after a character is entered, the program runs automatically. You do not need to press enter to confirm.-S: Hide the text color to the background color)
#!/bin/bashwhile read -n1 -s cdo echo -n "*"done
The input character is replaced by *. Of course, in the above example, if you enter the backspace key, the * number will not be deleted and will continue to be added ......
Read from File
Read reads a row from the file at a time. When the read is complete, read will exit and return a non-zero status code.
#!/bin/bashcount=0while read linedo count=$[ $count + 1 ]done < $1echo "$count line(s) in all."
If you use a pipeline to send data to read, a sub-shell will be enabled, so that you can view $ count outside the while, and you will find that it is still 0
Repost the following link
My blog address
Http://su1216.iteye.com/
Http://blog.csdn.net/su1216/