Linux shell command line options and parameter usage _linux shell

Source: Internet
Author: User
Tags builtin eval mkdir
Question Description: How do you deal with command-line options such as Tail-n Access.log in a Linux shell?
In bash, command line arguments can be handled in three ways, each with its own scenario.
1, direct processing, in turn to the $1,$2,..., $n, respectively, hand-handled;
2,getopts to handle the case of a single character option (such as:-N 10-f file.txt options);
3,getopt, you can handle a single character option, or you can handle long options long-option (such as--prefix=/home, etc.).
Summary: Small script manual processing can, getopts can handle most of the situation, getopt more complex, more powerful function.
1, directly handle position parameters manually
You have to know a few variables,
 code as follows:

* $: That is, the command itself, equivalent to C + + argv[0]
* $: First parameter.
* $, $ $, $ ... : 2nd, 3, 4 parameters, and so on.
* Number of $# parameters, excluding the command itself
* $@: A list of the parameters themselves, and does not include the command itself
* $*: Same as $@, but "$*" and "$@" (quoted) and different, "$*" interprets all parameters as a string, and "$@" is an array of arguments.

Manual processing can meet the majority of simple requirements, with shift use can also build a powerful function, but the processing of complex options suggested in the following two methods.
example, (getargs.sh):

 code as follows:

#!/bin/bash
If [$#-lt 1]; Then
echo "error. Need args "
Exit 1
Fi
echo "Commond is $"
echo "Args are:"
For ARG in "$@"
Todo
Echo $arg
Done


To run the command:

code as follows:

./getargs.sh CC
Commond is./getargs.sh
Args are:
11
22
Cc

2,getopts (Shell built-in command)
Handling command-line arguments is a similar and complex thing, and for this reason, C provides getopt/getopt_long functions, and C + + offers the options library, in the shell, the getopts and getopt.
The difference between getopts/getopt is that getopt is an external binary file, and getopts is shell builtin.

code as follows:

[Root@jbxue ~]$ type getopt
Getopt is/usr/bin/getopt
[Root@jbxue ~]$ type getopts
Getopts is a shell builtin

Getopts cannot directly handle long options (e.g.--prefix=/home, etc.)
For getopts use, you can search for a man bash 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 ":" to indicate that the character has its own parameters. Getopts gets these parameters from the command and deletes the "-" and assigns it to the second argument, which is assigned to "Optarg" if it has its own arguments. The shell that provides the getopts has the Optarg this variable, getopts modifies the variable.
Here the variable $optarg stores the parameters of the corresponding option, and $optind always stores the next element position to be processed in the original $*.
While getopts ": A:BC" opt #第一个冒号表示忽略错误 the colon after the character indicates that the option must have its own argument
example, (getopts.sh):

 code as follows:

Echo $*
While getopts ": A:BC" opt
Todo
Case $opt in
A) echo $optarg
Echo $optind;;
(b) echo "B $optind"
(c) echo "C $optind";;
? ) echo "Error"
Exit 1;;
Esac
Done
Echo $optind
Shift $ (($optind-1))
#shift $ (($optind-1)), the $* only retains the parameters to remove the contents of the option, which can then be handled normally by Shell programming.
echo $
Echo $*


To execute a command:

 code as follows:

./getopts.sh-a 11-b-C
-A 11-b-C
11
3
B 4
C 5
5
./getopts.sh

3,getopt (an external tool)
The specific use can be man getopt
#-o represents a short option, and a two colon indicates that the option has an optional parameter, and the optional parameter must be pressed close to the option, such as-carg and not-c ARG
#--long represents long option
example, (getopt.sh):

 code as follows:

#!/bin/bash
# A small example program for using the ' new Getopt (1) program.
# This program'll only work with Bash (1)
# an similar program using the TCSH (1) script. Language can be found
# as Parse.tcsh
# example input and output (from the bash prompt):
#./parse.bash-a par1 ' Another arg '--c-long ' wow!*\ '-cmore-b ' very long '
# Option A
# option C, no argument
# option C, argument ' more '
# option B, argument ' very long '
# remaining arguments:
#--> ' Par1 '
#--> ' another arg '
#--> ' wow!*\? '
# This we use ' "$@" ' to let each command-line parameter expand to a
# separate word. The quotes around ' $@ ' are essential!
# We need temp as the ' eval set-' would nuke ' return value of getopt.
#-o represents a short option, and a two colon indicates that the option has an optional parameter, and optional arguments must be pressed close to the option
#如-carg instead of-c ARG
#--long represents long option
# "$@" is explained above.
#-N: Information when an error occurs
#--To give an example of better understanding:
#我们要创建一个名字为 "-F" directory What are you going to do?
# mkdir-f #不成功, because F is parsed by mkdir as an option, you can use the
# mkdir---F so-F will not be taken as an option.
Temp= ' Getopt-o ab:c::--long a-long,b-long:,c-long:: \
-N ' example.bash '--"$@"
If [$?!= 0]; Then echo "Terminating ..." >&2; Exit 1; Fi
# Note the quotes around ' $temp ': they are essential!
#set rearrange the order of the parameters, which is to change the value of the $1,$2 ... $n, these values are rearranged in the getopt.
Eval set--"$temp"
#经过getopt的处理, the following handles the specific options.
While true; Todo
Case "$" in
-a|--a-long) echo "option A"; shift;;
-b|--b-long) echo "option B, argument \ ' $"; Shift 2;;
-c|--c-long)
# C has an optional argument. As we are in quoted mode,
# an empty parameter would be generated if its optional
# argument is not found.
Case "$" in
"") echo "option C, no argument"; Shift 2;;
*) echo "option C, argument \ ' $ '"; Shift 2;;
ESAC;;
-) shift; break;;
*) echo "Internal error!"; Exit 1;;
Esac
Done
echo "Remaining arguments:"
For Arg do
Echo '--> ', ' $arg ';
Done

To run the command:
 code as follows:

./getopt.sh--b-long abc-a-c33 remain
Option B, argument ' abc '
Option A
Option C, argument ' 33 '
Remaining arguments:
--> ' remain '

The above is a detailed description of the Linux shell command-line options and parameter usage, and I hope it helps.
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.