Basic knowledge of shell script 4-process user input

Source: Internet
Author: User

When the script needs to interact with the person running the script.

BASH Shell provides command line parameters (data values added after the command), command line options (single character values for modifying Command Behavior), and direct reading of keyboard input.

1. Command Line Parameters

The most basic way to pass data to shell scripts is to useCommand Line Parameters.

(1) read Parameters

The variable for reading input parameters isLocation parametersThe location parameter is represented by a standard number,

Where$0 indicates the program name., $1 is the first parameter, $2 is the second parameter, and so on until $9 is the ninth parameter.

The shell script automatically assigns the command line parameter values to each location variable.

You must useSpace separation (to include space in the parameter value, you must use single or double quotation marks)

When there are more than 9 parameters, you must use braces in the shell script to enclose the variables, for example, ${10 }. You can use any parameter.

(2) read program name

The string passed to the variable $0 is actually the program path (depending on the call method, the relative or absolute path is determined ).

UseBasenameCommand to remove the path prefix and only get the program name (the name cannot contain spaces ).

(3) test script

An error occurs when the script considers that it should contain parameters but does not actually have data.

A good way is to check the parameters to ensure that data exists before the parameters are used. You can use the-n parameter to check the data.

Ex: If [-N "$1"] Then... else... Fi

2. Special parameter variables

Used to track command line parameters

(1) parameter count

UseSpecial variable $ # Number of command line parameters contained in the test execution script. $ # Can be used anywhere in the script #

Ex: If [$ #-ne 2], you can test the number of parameters.

You can use $ {! #} To return the last command line parameter (when there is no parameter, $ # is 0, and $ {! #} Is the program name)

(2) retrieve all data

Variable $ * process all parameters provided in the command line as a wordMultiple parameters are considered as one parameter.

Variable $ @ process all parameters provided in the command line as multiple words in the same string. Allow iteration of the values (for is generally used) to separate different parameters.

3. Shift

ShiftThe command can change the relative position of the command line parameters.By default, each parameter variable is moved to the left position.(Variable $0 remains unchanged,Discard $1. Note that it cannot be recovered !)

When the number of parameters is unclear,This is a good way to iterate parameters..

You can provide a parameter for shift to realize multiple displacement changes..

4. processing options

The option is a single letter guided by a broken number, used to change the behavior of the command.

(1) Find the options

1) Processing simple options

You can use the methods that process the same command line parameters to process options,Use the case statement to determine whether the selected format is correct.

2) Separate options from Parameters

When both options and parameters are used, you can use -- to indicate the end of the Option List. After -- is found, shell will know that the following is a common parameter, and stop using the case processing option.

3) process the option with a value

Option followed by parameter value,One way is to use shift and the last read parameter after corresponding options in case.. The better method is as follows:

(2) Use the getopt command

The getopt command is used to process options and parameters.It is very convenient. It re-organizes parameters to facilitate resolution

1) Command Format

Getopt can accept any form of options and parameter lists, and automatically convert them to the appropriate format.

Command Format:GetoptOptions optstring Parameters

The opstring is used to define the valid option letters in the command line and the option letters that require parameter values.

2) use getopt in the script

Need to useSetThe command replaces the existing command line options and parameters with the format generated by the getopt command.

You need to send the command line parameter of the original script to the getopt command, and then output the getopt command to the set command, as follows: set-'getopts-q AB: CD "$ @"'

However, the getopt command cannot properly process the parameter values with spaces,It resolves spaces as parameter delimiters, rather than combining the two values caused by double quotation marks into one parameter. The solution is as follows:

(3) More advanced getopts commands

The getopts command processes existing shell parameter variables in sequence. Each call only processes one of the parameters detected in the command. After all the parameters are processed, the system exits with an exit state greater than 0.

It is very suitable for parsing all command line parameters in a loop

Format: getopts optstring variable

$ Optarg contains the value to be used by the option that requires the parameter value. $ optind contains the position in the parameter list when getopts stops processing.

Note: When getopts is processed, the-before the option is removed, so the corresponding case does not require a break number.

Good features:

1) The parameter value can contain spaces.

2) There can be no space between option letters and parameter values

3) bind all undefined options found in the command line to a single output -- question mark

5. Standardized options

Some letter options have a standard meaning. It is best to define the meaning of the option according to the standard meaning.

-A-c-d-e-f-h-I-l-N-o-Q-r-s-v-x-y

6. Get user input

To obtain the input from the script execution personnel during execution, useReadCommand

(1) Basic read

ReadThe command Accepts standard input or other file descriptor input. Read the data into a standard variable.

-PYou can specify a prompt in the READ command line.

Multiple variables can be specified or not specified (will be placed in the reply environment variable)

(2) Timing

Use-t to specify a timerWhen the number of times is full, the read operation returns a non-0 exit status.

Use-N to specify the number of characters enteredWhen the input reaches the predefined number, the input is automatically ended.

(3) silent reading

Use-s to make the input not displayed on the terminal(For example, enter the password)

(4) reading files

The most common method is to use the cat command and pass the while statement containing read through the pipeline.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.