A detailed explanation of the parameters in the shell in Linux

Source: Internet
Author: User
Tags case statement

The method of parameter passing in shell script is commonly used in 8 kinds

1. $# the number of parameters passed to the script

2. $* displays all parameter variables passed to the script in a single string. Unlike positional variables, this option argument can exceed 9

3. The current process ID number of the $$ script run

4. $! Process ID number of the last process running in the background

5. $@ and $ #相同, but use quotes and return each argument in quotation marks

6. $-Displays the current options used by the shell, as is the SET command function

7. $? Displays the exit status of the last command. 0 indicates no error, any other value indicates an error

8. $ () inside the command, you can execute the command in the script and return the output of the command execution

Let me give you an in-depth analysis

1, command line parameters

The most basic way to pass data to a shell script is to use command-line arguments.

(1) Reading parameters

Variables that read the input parameters are positional parameters, and positional parameters are represented by standard numbers.

Where $ is the program name, the first argument, the second argument, and so on, until the $ $ is the Nineth parameter.

The shell script automatically assigns command line arguments to each position variable.

When you enter more than one argument (either numeric or string), you must use a space-delimited (you must use single or double quotes if you want to include spaces in the parameter values)

When there are more than 9 arguments, you must enclose the variable in the shell script, such as ${10}, using curly braces. So that you can use any of the parameters.

(2) Read program name

The string passed to the variable $ is actually the path to the program (depending on the calling method to determine whether it is a relative or absolute path).

Use the basename command to remove the path prefix and obtain only the program name (no spaces are allowed in the name).

(3) test script

An error occurs when the script thinks that it should contain parameters but actually has no data.

A good way to do this is to check the parameters to make sure that the data exists before using the parameters, and you can use the-n parameter to check.

ex:if [–n] then. else.. Fi

2, the special parameter variable

Used to track command line arguments

(1) Parameter count

Use a special variable $ #测试执行脚本时包含的命令行参 number of numbers. You can use $# anywhere in your script

Ex:if [$#–ne 2] to test the number of parameters

You can use ${!#} to return the last command-line argument (when there is no argument, $ #为0, and ${!#} is the program name)

(2) Get all the data

Variable $* handles all the arguments provided in the command line as a single word, which takes multiple parameters as one argument.

Variable $@ handles all the arguments provided in the command line as multiple words in the same string. Allows the values to be iterated (generally using for), separating different parameters

3. Shift

The shift command can change the relative position of the command line arguments. Default to move each parameter variable to the left one position (variable $ unchanged, discard, note that you can not recover!) )

This is a good way to iterate over parameters without knowing the number of parameters.

You can provide a parameter for shift to achieve multiple-shift changes.

4, processing options

An option is a single letter that is booted by a dash to change the behavior of the command.

(1) Find the option

1) Processing Simple options

You can use the same method processing options as the command-line arguments to use the case statement to determine whether the option format is eligible.

2 separating options from parameters

When you use both options and parameters, you can use--to indicate the end of the list of options. Discover--After the shell knows the generic parameters, stop using the case processing option.

3 processing of options with values

Option followed by the parameter value, one method is to use shift and read the latter parameter after the corresponding option in the case. A better approach is as follows:

(2) using the getopt command

The getopt command is handy when working with options and parameters. It organizes the parameters to facilitate parsing

1) command format

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

The command format is: getopt options optstring Parameters

The option string (opstring) is used to define valid option letters in the command line, and which option letters require parameter values.

2 Use getopt in scripts

You need to use the SET command to replace existing command-line options and parameters with the formatted form generated by the getopt command.

You need to give the original script command-line arguments 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 does not handle parameter values with spaces very well, and it resolves the spaces into parameter delimiters instead of merging two values from double quotes into one argument. The solution is as follows:

(3) More advanced getopts command

Getopts the order of command to handle existing shell parameter variables, one at a time, processing only the parameters detected in the command. After all parameters have been processed, exit with an exit state greater than 0.

Ideal for parsing all command-line arguments in a loop

The format is: getopts optstring variable

$OPTARG The value that contains the option to use for the parameter value $OPTIND contains the position in the argument list when getopts stops processing.

Note: When getopts is processed, the previous option is removed, so no dashes are required in the corresponding case.

Good features:

1 can include spaces in parameter values

2 There can be no space between the option letter and the parameter value

3 The undefined options found on the command line are bound to a single output-the question mark

5. Standardized options

There are some letter options that have the standard meaning. It's best to define option meaning by standard meaning

-a–c–d–e–f–h–i–l–n–o–q–r–s–v-x–y

6. Get user input

When you need to obtain input from the execution script during execution, use the Read command

(1) Basic reading

The read command accepts standard input or other file descriptor input. After reading, put the data into a standard variable.

-P allows you to specify a prompt directly on the read command line.

You can specify multiple variables, or you can not specify (will be placed in the reply environment variable)

(2) Timing

Use-T to specify a timer that is full and not entered, and read returns a non-0 exit state.

Use-N to specify the number of characters you enter, and then automatically end the input when you reach a predetermined number

(3) Reading silently

Use-s to make input not appear in the terminal (for example, enter a password)

(4) Read files

The most common method is to use the Cat command and pass it to the while statement containing read.

Ex:cat Test | While Read line

To give you more insight into some examples

#!/bin/bash
#extracting command text_text_text_line options as parameters

Help_info () {
echo "NAME"
echo "\t$0"
echo "Synopsis"
echo "\t$0 is a shell test about process Options"
echo "DESCRIPTION"
echo "\toption like-a-B param1-c param2-d"
}

If [$#-lt 0]
Then
Help_info
Fi

Nomal_opts_act ()
{
Echo-e "\n### nomal_opts_act ###\n"

While [-N ' $]
Todo
Case "$" in
-a)
echo "Found the-a option"
;;
-B)
echo "Found the-b option"
echo "The parameter follow-b is $"
Shift
;;
-c)
echo "Found the-c option"
echo "The parameter follow-c is $"
Shift
;;
-D)
echo "Found the-d option"
;;
*)
echo ' not ' option '
;;
Esac
Shift
Done
}

#用shell命令自建的选项解析, you can follow your own ideas.
#优点: Customized, not to do, only unexpected
#缺点: Trouble

Getopt_act ()
{
Echo-e "\n### getopt_act ###\n"

getoptout= ' getopt ab:c:d ' $@ '
Set--$GETOPTOUT
While [-N ' $]
Todo
Case is in
-a)
echo "Found the-a option"
;;
-B)
echo "Found the-b option"
echo "The parameter follow-b is" $ "
Shift
;;
-c)
echo "Found the-c option"
echo "The parameter follow-c is" $ "
Shift
;;
-D)
echo "Found the-d option"
;;
--)
Shift
Break
;;
*)
echo "unknow option:" "$"
;;
Esac
Shift
Done

Param_index=1
For param in "$@"
Todo
echo "Parameter $param _index: $param"
param_index=$[$param _index + 1]
Done
}

#用getopt命令解析选项和参数
#优点: The relative and getopts is a semi-automatic parsing, automatic organization of options and parameters, with--symbols to separate options from parameters
#缺点: Relative to Getopts's shortcomings
#1. Need to match set--command, not required, manual shift
#2. Spaces are not supported in option parameters such as-a-b dog-c "Earth Moon"-d-f param1 param2 will parse errors

Getopts_act ()
{
Echo-e "\n### getopts_act ###\n"
While Getopts:ab:c:d ARGS
Todo
Case $ARGS in
A
echo "Found the-a option"
;;
b
echo "Found the-b option"
echo "The parameter follow-b is $OPTARG"
;;
C
echo "Found the-c option"
echo "The parameter follow-c is $OPTARG"
;;
D
echo "Found the-d option"
;;
*)
echo "unknow option: $ARGS"
;;
Esac
Done

Shift $[$OPTIND-1]
Param_index=1
For param in "$@"
Todo
echo "Parameter $param _index: $param"
param_index=$[$param _index + 1]
Done
}

#getopts command resolution options and parameters
#优点: can include spaces in parameters such as:-C "Earth Moon"
# there can be no spaces between the option letters and the parameter values:-bdog
# can bind undefined options to? output
# unknow option:?

Nomal_opts_act-a-B dog-c earth-d-F param1 param2
Getopts_act-a-B dog-c "Earth Moon"-d-f param1 param2
Getopt_act-a-B dog-c earth-d-F param1 param2

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.