Linux bash shell (14): command line options

Source: Internet
Author: User

This article is one of the book notes in Chapter 6 "learning the bash shell" 3rd edition "command-line options and typed varilables, but we will not limit this article.

In Linux commands, parameters such as [-Option] are often included. There may be 0 or more options in the command line. We learned the location parameters before, including $1, $2, $3 ..., $ *, $ #, See Linux bash shell Learning (7): shell programming basics-run shell scripts and functions
. These location parameters are read-only.

Shift

Shift provides the operation of assigning values to the value of the read-only location parameter. Values of 1 = $2 = $3 ,..., Shift N can be used to specify the number of shifts. For example, shift 3 indicates 1 = $4, 2 = $5 ,.... If the command line contains [-options], we can judge them and perform shift processing. A simple example is as follows:

If [$1 =-O]; then



[Process the-O option]



Shift

Fi


[Normal processing of arguments...]

The following two examples show how to use shift to check parameters.

# Example 1: The-N parameter may exist and is the first parameter. If the first parameter is-N, it is recorded in howmany, shift it, and place $2 at $1. If the first parameter is-X, but X is not a number, give a warning statement. Otherwise, howmany uses the default value-10.

Function test1

{

# For grep, ^ indicates starting from the beginning of the matched row, $ indicates matching the end of the row, and here it indicates the entire $1 match, instead of partial match, * indicates that the first character matches 0 or more characters. The following [0-9] * indicates that the character is followed by 0 or multiple numbers, [0-9] [0-9] * indicates that the number is followed by 0 or multiple numbers. Therefore, echo $1 | grep '^-[0-9] [0-9] * $' indicates the matching format-N, where N is a number. For more information about how to use grep, see http://www.yesadmin.com/301/135287/index.html.

# $ (Command) indicates the content of command execution.

#-N str. the string is not null and the length must be greater than zero.

# Note the use of double quotation marks, indicating that this is a str to be checked

If [-n"$ (Echo $1 | grep '^-[0-9] [0-9] * $ ')"
]; Then

Howtasks = $1

Shift


Elif [-n "$ (echo $1 | grep '^-')"]; then

Echo 'usage: test1 [-N] filename'


Exit 1

Else

Howbid = "-10"

Fi

Echo "sort-nr $1 | head $ howmany"

}

Test1-5 $ file

For multiple parameters, it is assumed that they can only be placed before other parameters, as shown below. For the-B option, the parameter [-B Barg] Must be included. For-B, one more bit is required.

While [-n "$ (echo $1 | grep '-')"]; do

Case $1 in

-)[Process option-A]
;;


-B)[Process option-B, $2 is the option's argument]


Shift
;;

-C)[Process option-C]
;;


*) Echo 'usage: alice [-a] [-B barg] [-c] args ...'


Exit 1


Esac

 Shift

Done

[Normal processing of arguments...]

However, this method cannot solve the following two problems: 1. You cannot use-ABC to replace-a-B-c; 2. You cannot use-Barg to replace-B Arg, however, these two methods are common in Linux commands. We can use the getopts built-in command to handle the problem:

Getopts

Getopts has two parameters. The first parameter is a string, including the character and ":". Each character is a valid option. If the character is followed by ":", this character has its own parameters. Getopts obtains these parameters from the command, deletes "-", and assigns it to the second parameter. If it has its own parameter, this parameter is assigned to "optarg. The following example uses the getopts method. We will write it as an executable example.

Echo "--- Test 3 ---"


Function test3

{

Echo "test3 $ @"


# OPTIND records the parameters for preparing the analysis (that is, the next analysis). If we do not use the function, but directly use it as a script, OPTIND will be reinitialized every time it is executed, however, if we use the function method, OPTIND will keep the last value, that is, getopts will analyze the nth parameter, for example, the first parameter, so unset is required to ensure correctness. If-AB is used to represent-a-B, after-a is analyzed, OPTIND does not add a value and the original value is maintained. The parameter of this position will be analyzed next time. If-B arg, then, OPTIND is added to the second node. So we do not need to shift in getopts. We can perform shift $ ($ OPTIND-1) after all getopts analyses are completed ))


Echo "optind = $ optind"


Unset optind

# If we use "AB: C", if option is not required, we will report illegal option-D and so on. If we remove the relevant information, the first parameter of getopts will be ":. Of course, you can also set the Environment Parameter opterr to 0. If it does not match, set the obtained parameter value "? ", In the following example, the fourth option can be /?) Or *).

WhileGetopts ": AB: C" opt
; Do

Echo-n "optind = $ optind :"


Case $ opt in

A) echo "process option-$ Opt ";;

B) echo "process option-$ opt, $ optarg is the option's argument ";;

C) echo "process option-$ Opt ";;

# The following is equivalent to *), because opt is set "? "


/? ) Echo "process option-$ opt"

Echo 'usage: alice [-a] [-B barg] [-c] args ...'

Exit 1

Esac

Done

Echo "OPTIND = $ OPTIND, shift $ ($ OPTIND-1 ))"

Shift $ ($ optind-1 ))


Echo "test $ @"

Echo "normal processing of arguments ..."

}

Test3-B hello-a-c OK

Echo

Test3-bhello-ac OK

Echo

Test3-AB Hello OK

Echo

Test3-d

If the command parameters adopt the option method, getopts can provide a flexible analysis method. In addition, for non-matching options, that is "? "Options, you can also get the command parameters, you can get the location of the location parameter according to $ (OPTIND-1), and then get the specific content of the parameter.

Related Links: My articles on Linux operations

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.