Shell system learning to pass parameters to Shell scripts

Series Article Directory

Shell system learning what is Shell

Shell system learning to create a Shell program

Shell system learning to pass parameters to Shell scripts

Shell system learning how to execute Shell programs

Shell variables and references for Shell system learning

 Shell conditional test, judgment statement and operator for Shell system learning

 The loop structure of Shell system learning

 Functions of Shell System Learning

Array of Shell System Learning

Systematic learning of regular expressions in Shell

File operation for Shell system learning

The son of Shell system learning Shell and process processing


Parameters passed to a shell script from the command line are also called positional parameters, because the shell script receives their values ​​according to the position of the parameters. Inside the Shell script, users can obtain parameters through a series of system variables whose names are fixed and simple. Listed in the table below:

Common System Parameters
variable name illustrate
$n Indicates the nth parameter passed to the script, for example, $1 represents the first parameter passed, $2 represents the second parameter, and so on
$# The number of parameters passed in
$0 current script name
$* Returns the value of all parameters in the form "parameter1 parameter2..."
$@ Returns the value of all parameters in the form "parameter1" "parameter2"...
$_ last parameter

 Notice:

  • A string enclosed by single quotes or double quotes is passed as a parameter, and the quotes will be removed when passing
  • For parameters containing space characters or other special symbols, you need to use single quotes or double quotes to avoid misparsing. If there are spaces or other special characters in the parameters, you cannot use $* to get all parameters, but use $@.
  • $#The number of parameters returned, excluding $0.
  • If the parameters passed by the user are greater than 9, $10 cannot be used to represent the 10th parameter. In order to obtain the 10th parameter, the user tourmaline processes or saves $1 first, then uses the shift command to delete parameter 1 and move all remaining parameters down by 1, at this time the 10th parameter becomes $9, and so on. The value of $# will be updated to reflect the remaining number of parameters. In this way, the code is better iterated.

Write a script like this:

#!/bin/bash
echo "$# paramters num"
echo "$@"
echo "$*"
echo $@
echo $*
echo $_

Execute the following commands and results:

eden_ubuntu@edenubuntu:~/Documents/Shell$ ./1-3.sh a "b c" d 111
4 paramters num
a b c d 111
a b c d 111
a b c d 111
a b c d 111
111

parameter expansion

For simple cases, the above system variables are sufficient as well. In practice, however, users do not always encounter such simple situations. For example, the ls command we often use, we can enter

ls -l
ls -la
ls -lrt

Wait for different parameters to perform different operations, so simply using $1, $2... can no longer meet the requirements. At this time, we need to use parameter expansion , and use the getopts command in the Shell program. Next, we will talk about how to use it in detail it.

getopts

getopts is a command supported by bash . The basic syntax of getopts is as follows:

getopts optstring [arg]

optstring is a string containing a list of option names recognized by the getopts command. We let s denote a character, where the syntax is:

option content illustrate
       : If optstring starts with:, it means silent mode, ignoring general error messages
      s A valid option without an argument value following
      s: Valid options and must be followed by parameter values

getopts will traverse each option in turn and save the option name to arg , and OPTARG will save the parameter value for the option.

Let us illustrate with an example:

#!/bin/bash

#input paramters index
echo "OPTIND starts at $OPTIND"
#get paramters
while getopts ":pq:" optname
 do
 case "$optname" in
        "p")
          echo "Option $optname is specified"
          ;;
        "q")
          echo "Option $optname has value $OPTARG"
          ;;
        "?")
          echo "Unknown option $OPTARG"
          ;;
        ":")
          echo "No argument value for option $OPTARG"
          ;;
        *)
          # Should not occur
          echo "Unknown error while processing options"
          ;;
 esac
 echo "OPTION is now $OPTIND"
done

":pq:" means:

getopts ignores error messages; no parameters after -p, parameters after -q

OPTIND is a system variable, indicating the subscript position of the current getopts request parameter

 Execute the following commands and results:

eden_ubuntu@edenubuntu:~/Documents/Shell$ ./1-4.sh -p -q 12
OPTIND starts at 1
Option p is specified
OPTION is now 2
Option q has value 12
OPTION is now 4

Note that the following commands also have the same effect:

eden_ubuntu@edenubuntu:~/Documents/Shell$ ./1-4.sh -pq 12
OPTIND starts at 1
Option p is specified
OPTION is now 1
Option q has value 12
OPTION is now 3

This shows that both -p -q 12 and -pq 12 can achieve our goal. So options can be used together, just like the ls command we usually use: ls -lrt is equivalent to ls -l -r -t.

So what if we want the option to support wide-format, for example, when using cmake:

cmake -DCMAKE_TOOLCHAIN_FILE=arm-toolchain.cmake .

This kind of getopts is not supported! ! ! We need to use another command getopt

topped

Unlike getopts, which is a built-in command of bash, getopt is an external command, which is different from the usual Linux distributions.

We can see the difference by using the type command

eden_ubuntu@edenubuntu:~/Documents/Shell$ type getopts
getopts is a shell builtin
eden_ubuntu@edenubuntu:~/Documents/Shell$ type getopt
getopt is hashed (/usr/bin/getopt)

getopt supports short options and long options, -o or --option followed by short options, -l or --long followed by long options

If the parameter is optional, the value of the short option must be close to the option, for example -carg instead of -c arg; for long options, use "=" between the value and the option, for example -clong=arg instead of -clong arg.

#!/bin/bash

echo original parameters=[$@]

#-o或--options选项后面是可接受的短选项,如ab:c::,表示可接受的短选项为-a -b -c,
#其中-a选项不接参数,-b选项后必须接参数,-c选项的参数为可选的
#-l或--long选项后面是可接受的长选项,用逗号分开,冒号的意义同短选项。
#-n选项后接选项解析错误时提示的脚本名字
ARGS=`getopt -o ab:c:: --long along,blong:,clong:: -n "$0" -- "$@"`
if [ $? != 0 ]; then
    echo "Terminating..."
    exit 1
fi

echo ARGS=[$ARGS]
#将规范化后的命令行参数分配至位置参数($1,$2,...)
eval set -- "${ARGS}"
echo formatted parameters=[$@]

while true
do
    case "$1" in
        -a|--along) 
            echo "Option a";
            shift
            ;;
        -b|--blong)
            echo "Option b, value=$2";
            shift 2
            ;;
        -c|--clong)
            case "$2" in
                "")
                    echo "Option c, no value";
                    shift 1  
                    ;;
                *)
                    echo "Option c, value=$2";
                    shift 2;
                    ;;
            esac
            ;;
        --)
            shift
            echo "shift"
            break
            ;;
        *)
            echo "Internal error!"
            exit 1
            ;;
    esac
done

Execute command and result:

eden_ubuntu@edenubuntu:~/Documents/Shell$ ./1-5.sh -a -b 1 --clong=2
original parameters=[-a -b 1 --clong=2 test1 test2]
ARGS=[ -a -b '1' --clong '2' -- 'test1' 'test2']
formatted parameters=[-a -b 1 --clong 2 -- test1 test2]
Option a
Option b, value=1
Option c, value=2
shift

If --clong=2 is changed to -clong 2, the result is as follows:

eden_ubuntu@edenubuntu:~/Documents/Shell$ ./1-5.sh -a -b 1 --clong 2 test1 test2
original parameters=[-a -b 1 --clong 2 test1 test2]
ARGS=[ -a -b '1' --clong '' -- '2' 'test1' 'test2']
formatted parameters=[-a -b 1 --clong -- 2 test1 test2]
Option a
Option b, value=1
Option c, no value
shift

option c shows no parameter value

The above is the entire content of this article, mainly the part related to shell passing parameters

Guess you like

Origin blog.csdn.net/MashiMaroJ/article/details/125583142