Linux shell Scripting--Using structured commands (iv)

Source: Internet
Author: User
Tags polyline

Command-line arguments

The most basic way to pass data to a shell script is to use command-line arguments, which allow you to add data values to the command line when you run the script

Reading parameters

Bash Shell assigns some special variables called positional parameters to all parameters entered by the command line, even the name of the program executed by the shell, which is the program name, $ $ is the first argument, and the second argument

Code 4-1

[Email protected]:/data# cat demo1 #!/bin/bashfactorial=1for (i=1;i<=$1;i++) do        factorial=$[$factorial * $i] Doneecho "The factorial of $factorial" [email protected]:/data#./demo1 5The factorial of 5 is 120


Enter more command items separated by a space

Code 4-2

[Email protected]:/data# cat Demo2 #!/bin/bashsum=$[$ + $]echo "The first parameter is" echo "the second parameter I  S $ "echo" The sum is $sum "[e-mail protected]:/data#./demo2 3 5The First parameter is 3The second parameter are 5The sum is 8

If there are spaces when entering as a string, you must use single or double quotation marks

Code 4-3

[Email protected]:/data# cat Demo3 #!/bin/bashecho ' Hello $1,glad to meet ' echo ' Hello $2,glad to meet ' [email prote cted]:/data#./demo3 John "Rich Blum" Hello John,glad to meet Youhello Rich Blum,glad to meet


If the script requires more than 9 Elder command line arguments, you need to add braces around the numbers such as: ${10}, ${11}

Code 4-4

[Email protected]:/data# cat Demo4 #!/bin/bashsum=$[+ $11]echo "The tenth paramter is ${10}" echo "The eleventh Param ter is ${11} ' echo ' The sum is $sum ' [email protected]:/data#./demo4 1 2 3 4 5 6 7 8 9 11The Tenth paramter is 10The ele Venth paramter is 11The sum is 21


When the real string passed to the $ variable is the path to the entire script, the entire path is used in the program, not just the program name

Code 4-5

[Email protected]:/data# cat demo5 #!/bin/bashecho "The command entered is: $" [Email protected]:/data#/data/demo5 the C Ommand entered is:/data/demo5[email protected]:/data#./demo5 the command entered is:./demo5


The basename command returns only the program name, not the path

Code 4-6

[Email protected]:/data# cat Addem #!/bin/bashname= ' basename $ ' if [$name = "Addem"]then        total=$[$ + $]elif [$n Ame = "Multem"]then        total=$[$]fiecho "the $total" [email protected]:/data#./addem 2 5The Total is 7[ Email protected]:/data# cp-s addem multem[email protected]:/data#./multem 2 5The Total is 10


You can use-N to check for data in command-line arguments, preferably with double quotation marks if you want to string compare command-line arguments

Code 4-7

[Email protected]:/data# cat Demo6 #!/bin/bashif [-N "$]then        echo" hello,$1 "Else        echo" Sorry, you do not Iden  Tify yourself "Fi[email protected]:/data#./demo6 tomhello,tom[email protected]:/data#./demo6 Sorry, you do not identify yourself


$ #特殊变量含有脚本运行时就有的命令行参数的个数

Code 4-8

[Email protected]:/data# cat Demo1 #!/bin/bashecho "There were $# parameters supplied" [email protected]:/data#./demo1 1 2 3 4 5There were 5 parameters supplied[email protected]:/data#./demo1 Tom "Hello World" there were 2 parameters supplied


Code 4-9

[Email protected]:/data# cat Demo2 #!/bin/bashif [$#! = 2]then        echo "Usage:demo2 a B" Else        sum=$[$ + $]        E Cho "The sum is $sum" Fi[email protected]:/data#./demo2 Usage:demo2 a b[email protected]:/data#./demo2 3usage:demo2 a B[e Mail protected]:/data#./demo2 3 5The sum is 8[email protected]:/data#./demo2 3 5 8usage:demo2 a B

Note: $ #虽然代表命令行参数的个数, but ${$#} does not display the last command-line argument of a variable

Use ${!#} to display the last parameter, or to #赋给一个变量param, and then also use the variable in the format of a special command-line parameter variable. Note, however, that $ #的值为0 when there are no arguments on the command line, but the ${!#} variable returns the name of the script used by the command line

Code 4-10

[Email protected]:/data# cat Demo3 #!/bin/bashecho "The last parameter is $#" echo "The last parameter was ${!#}" [Email PR otected]:/data#./demo3 the last parameter is 0The last parameter was./demo3[email protected]:/data#./demo3 1 2 3 4 5 6 The last parameter is 6The last parameter was 6


The $* and [email protected] variables provide quick access to all parameters, and the $* variable saves all arguments supplied on the command line as a single word, and the [email protected] variable will have all the parameters provided on the command line
Number as multiple independent words in the same string

Code 4-11

[Email protected]:/data# cat Demo4 #!/bin/bashcount=1for param in "$*" Do        echo "\$* Parameter # $count = $param"        ((c ount++) Donecount=1echo "——————————————————————" for param in "[email protected]" Do        echo "\[email protected] Parameter # $count = $param "        ((count++)) Done[email protected]:/data#./demo4 Hadoop Spring MyBatis Hibernate shiro$* P Arameter #1 = Hadoop Spring MyBatis Hibernate Shiro —————————————————————— [email protected] Parameter #1 = Hadoop[email Pro Tected] Parameter #2 = spring[email protected] Parameter #3 = mybatis[email protected] Parameter #4 = hibernate[email Prot Ected] Parameter #5 = Shiro


The shift command, by default, will reduce the index value of each parameter variable by 1, so the value of the variable $ $ will be moved to $ $, and the value of the variable will be moved to $ $, and the value of the variable will be deleted
(The value of the variable, that is, the program name does not change), each time the shift command is executed, the position of all parameters is moved by one

Code 4-12

[Email protected]:/data# cat Demo5 #!/bin/bashcount=1while [-n] "]do        echo" Parameter # $count = $ "        ((count++))        shiftdone[email protected]:/data#./demo5 Hadoop Spring MyBatis Hibernate shiroparameter #1 = hadoopparameter #2 = Sp Ringparameter #3 = Mybatisparameter #4 = Hibernateparameter #5 = Shiro


You can also provide a parameter to the shift command to perform a multi-bit move

Code 4-13

[Email protected]:/data# cat Demo6#!/bin/bashecho "The original parameters: $*" Shift 2echo "Here's the new first paramete R: $ "[email protected]:/data#./DEMO6 1 2 3 4 5 6The original Parameters:1 2 3 4 5 6Here ' s The new first Parameter:3


Processing options, which are a single letter following a single broken line, that can change the behavior of the command

The shell uses a special character (-) double broken polyline to indicate that the option is over, leaving the remaining command-line arguments to the subsequent program processing

Code 4-14

[Email protected]:/data# cat Demo1 #!/bin/bashwhile [-N "$]do Case" $ "in-a        ) echo" Found the-a option ";; -        B) echo "Found the-b option";;        -c) echo "Found the-c option";;        --) shift break            ;;        *) echo "is not a option";;        Esac        shiftdonecount=1for param in "[email protected] ' do        echo ' Parameter # $count: $param"        ((count++)) done [Email protected]:/data#./demo1-a-b-c test1 test2 test3found the-a optionfound the-b optionfound the-c optiontest1 is not a optiontest2 is not a optiontest3 is not a option[email protected]:/data#./demo1-a-b-c--test1 test2 test3 Found the-a optionfound the-b optionfound the-c optionparameter #1: test1parameter #2: test2parameter #3: Test3


The getopt command accepts a series of arbitrary command-line options and arguments and automatically converts them to the appropriate format
getopt optstring Options parameters
optstring defines the option letters that are valid for the command line, and each option letter that requires a parameter value is preceded by a colon
Code 4-15

[Email protected]:/data# getopt ab:cd-ab test1-cd test2 test3-a-B test1-c-D--test2 test3

As shown in code 4-15, optstring defines 4 valid option letters, a, B, C, and D. It also defines that the option letter B requires a parameter value, and when the getopt command runs, it checks the supplied argument list and parses it based on optstring. It automatically divides the-CD option into two separate options, and inserts the extra parameters in the split line between the two broken lines

As in code 4-16, if you highlight an option that is not in optstring, by default, the GETOPT command generates an error message, plus-Q to ignore the message:

Code 4-16

[Email protected]:/data# getopt ab:cd-ab test1-cde test2 test3getopt:invalid Option--' e '-a-b test1-c-D--test2 t Est3[email protected]:/data# getopt-q ab:cd-ab test1-cde test2 test3-a-B ' test1 '-c-d--' test2 ' test3 '


One of the options for the SET command is a double-broken polyline, which passes the command-line arguments of the original script to the getopt command, and then passes the output of getopt to the SET command, which replaces the command-line parameter value with the value passed to it.

Code 4-17

[email protected]:/data# cat Demo2 #!/bin/bashset--' getopt-q ab:c ' [email          protected] "While [-N" $ "]do case" $ in-a) echo "Found the-a option";; -b) param= "$" "echo" found-b option.        With parameter value $param "SHIFT;        -c) echo "Found the-c option";;        --) shift break;; *) echo "is not a option" Esac shiftdonecount=1for param in "[email protected]" do echo "Para Meter # $count: $param "((count++)) done[email protected]:/data#./demo2-acfound the-a optionfound the-c opt ion[email protected]:/data#./demo2-ab test1-cd "test2 test3" test4 test5found the-a optionfound-b option. With parameter value ' test1 ' Found the-c optionparameter #1: ' test2parameter #2: test3 ' parameter #3: ' test4 ' parameter # 4: ' Test5 ' 

As you can see from code 4-17, the getopt command is not good at handling parameter values with spaces, it treats spaces as parameter separators instead of using double quotes as a parameter, but fortunately, you can use getopts to solve this problem

Getopts handles only one parameter that is detected on the command line each time it is called. When all parameters are processed, it exits and returns an exit status code greater than 0

Getopts optstring Variable

The optstring in getopts is similar to the previous one, if the option letter requires a parameter value, add a colon, and if you want to remove the error message, precede the optstring with a colon

The getopts command uses two environment variables. If the option needs to be followed by a parameter value, the OPTARG environment variable will save the value. The OPTIND environment variable holds the parameter position that getopts is working on in the argument list

Code 4-18

[Email protected]:/data# cat Demo3 #!/bin/bashwhile getopts:ab:c optdo case        ' $opt "in        a) echo" Found the-a Optio n ";;        b) echo "fount the-b option, with value $OPTARG";;        c) echo "Found the-c option";;        *) echo "unknow option: $opt";;        Esacdone[email protected]:/data#./demo3-ab test1-cfound the-a optionfount the-b option, with value Test1found the-c Option[email protected]:/data#/demo3-b "test1 test2"-afount the-b option, with value test1 test2found the-a option[e Mail protected]:/data#./demo3-dunknow option:? [Email protected]:/data#./demo3-acdefound the-a optionfound the-c optionunknow option:? Unknow option:? [Email protected]:/data#./demo3-abtest1found the-a optionfount the-b option, with value test1

If the code 4-18,getopts can handle the parameter values that contain spaces well, it can uniformly output all undefined options found on the command line to a question mark, and the undefined option letters in optstring are sent to the code as question marks. You can also use option letters and parameter values together without adding spaces

Optind with the shift command to move parameters

Code 4-19

[Email protected]:/data# cat Demo4 #!/bin/bashwhile getopts:ab:cd optdo case        ' $opt "in        a) echo" Found the-a Opti On ";;        b) echo "fount the-b option, with value $OPTARG";;        c) echo "Found the-c option";;        D) echo "Found the-d option";;        *) echo "unknow option: $opt";;        Esacdoneshift $[$OPTIND-1]count=1for param in "[E-mail protected]" Do        echo "Parameter $count: $param"        ((count++ )) Done[email protected]:/data#./demo4  -ab test1-d test2 test3 test4found the-a optionfount the-b option, with Valu E test1found the-d optionparameter 1:test2parameter 2:test3parameter 3:test


Get user input

After the read command accepts the standard input, it puts the data into a standard variable

Code 4-20

[Email protected]:/data# cat Demo5 #!/bin/bashecho-n "Enter Your name:" Read Nameecho "Hello $name, Welcome to my program" [Email protected]:/data#./demo5enter your Name:tomhello Tom, welcome to my program


The Read command contains the-p option, allowing parameters to be received after the string, and the arguments and strings must be separated by spaces

Code 4-21

[Email protected]:/data# cat demo1 #!/bin/bashread-p "Enter Your Name:" First Lastecho "your name is $last. $first ... "[email protected]:/data#./demo1 Enter your Name:rich blumyour name is Blum. Rich ...


Read multiple inputs

Code 4-22

[Email protected]:/data# cat Demo6 #!/bin/bashread-p "Please enter your age:" agedays=$[$age * 365]echo "This makes you Over $days daysold "[E-mail protected]:/data#./demo6 Please enter your age:20that makes your over 7300 Daysold


If a variable is not specified in the Read command line, the received data is stored in the Special environment variable reply

Code 4-23

[Email protected]:/data# cat Demo2 #!/bin/bashread-p "Enter a number:" Factorial=1for ((i=1;i<= $REPLY; i++))        do factorial=$[$factorial * $i]doneecho "The factorial of $REPLY is $factorial" [email protected]:/data#./demo2 Enter a num ber:5the factorial of 5 is 120


Code 4-24


The read command will wait until the input is not entered, and the-t option specifies a timer, and when the timer expires, read returns a non-0 status code

Code 4-25

[Email protected]:/data# cat Demo4 #!/bin/bashecho "time: ' Date ' +%y-%m-%d%h:%m:%s" ' "If read-t 5-p" Please enter your NA Me: "Namethen         echo" Hello $name, Welcome to my script time: ' Date ' +%y-%m-%d%h:%m:%s "'" Else        echo "Sorry, too slow ! Time: ' Date ' +%y-%m-%d%h:%m:%s "'" Fi[email protected]:/data#./demo4 time:2016-12-04 16:06:06please Enter your name: Tomhello Tom, Welcome to my script time:2016-12-04 16:06:08 [email protected]:/data#./demo4 time:2016-12-04 16:06:12pleas E Enter your name:sorry, too slow! time:2016-12-04 16:06:17


You can use the Read command to count the characters entered, and when the input character reaches the preset number of characters, it automatically assigns the input data to the variable and begins the execution of the down program, and the-n
and 11 use, tell read command to accept single word specifier exit

Code 2-25

[Email protected]:/data# cat Demo5 #!/bin/bashread-n1-p "Do you want to continue [y/n]" Answercase $answer in         y|y) E Cho             echo "fine,continue on ...";;        N|n) echo             echo "Ok,goodbye"             exit;; Esacecho "This is the end of the script" [email protected]:/data#./demo5 does you want to continue [y/n]yfine,continue on]. . This is the end of the script


Hidden mode read, the-S option prevents the data passed to the read command from appearing on the monitor (the actual data is displayed, but the read command sets the text color to be the same as the background color)

Code 2-26

[Email protected]:/data# cat Demo6 #!/bin/bashread-s-P "Enter Your password:" Passecho echo "is your password really $pa SS "[email protected]:/data#./demo6 Enter your password:is your password really hello


Outputs the results of the cat through the pipeline to read

Code 2-17

[Email protected]:/data# cat text Springmybatishibernateshirohadoopspark[email protected]:/data# cat demo1 #!/bin/ Bashcount=1cat text | While read Linedo        echoes "line $count: $line"        ((count++)) Done[email protected]:/data#./demo1 Line 1:springline 2: Mybatisline 3:hibernateline 4:shiroline 5:hadoopline 6:spark


Linux shell Scripting--Using structured commands (iv)

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: 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.