Shell Programming (iii)

Source: Internet
Author: User
Tags case statement

In the first two articles, we have mastered some of the basic syntax of the shell, the use of variables, and the operation of basic data types. So this time we will learn the shell's structured commands, which are conditional selection statements and looping statements in our other programming languages.

However, when you learn shell-structured commands, we will find that it differs from other programming languages. Let's start here:

Condition selection

In the conditional selection statement, there are several ways to do this:

If-then statements
if commandthen    COMMANDSFI

 
例如:






Eat the melon crowd to show a face to be confused: The IF statement followed by the command, in our other programming languages, here is the return of the Boolean value (true,false) expression.

So what the hell is going on here?

The IF in the shell script is actually based on the exit status code of the subsequent command to determine whether to execute the subsequent statement.

For the exit status code, you just need to remember: normal exit (command execution is normal) the status code is 0, abnormal exit status code is not 0 (there are many).

The semantics of the above statement are: If the command after the if is performed normally (status code 0), then the statement after then is executed. Otherwise, it is not executed. The FI represents the end of the IF statement.

#!/bin/bash# here because the PWD is a Linux built-in command, it exits normally after execution (status code 0), so the statement in then is executed # if this is replaced by a nonexistent command (for example, PW), it will exit abnormally. The statement in then is not executed if  pwdthen   Echo executes then inside the statement fi

 

If-then can also be shortened to

if command; then    COMMANDSFI.

 

Therefore, the above code can also be written as follows:

#!/bin/bashif  pwd; then   Echo executes the statement inside then the fi

 

Above, what should I do if I want to determine the handling of abnormal exits (status code not 0)?

Don't worry: else to help you.

If-then-else statements
if commandthen    Commandselse    COMMANDSFI

 

This returns an else statement compared to the If-then statement, and the Else statement is used to determine if the command after the if is not properly exited.

#!/bin/bashif  pwdthen    echo Normal exit else     echo Abnormal exit fi   

Even, we can deform and write more else:

if Command1 then    commands elif     Command2 then    command3fi

 

But the above can only be based on exit status code to judge, can't write expression, you also let me how to write? I amputated you directly in every programming language!

Don't panic, sir, please look down:

Test command

The test command is used in If-then or IF-THEN-ELSE statements, primarily to determine whether the listed conditions are true, and if so, exits and returns exit status code 0, otherwise it returns non 0.

This means that we can write an expression command by using the test command. However, for programs that are accustomed to other programming languages apes (except those not learned), do not be happy too early, there is a pit ahead, as to what the pit, can be seen later.

Let's take a look at the basic usage of the test command:

Direct use:

Test condition

 

Combining If-then statements With

if   test Conditionthen    COMMANDSFI

Combining If-then-else statements With

if   test conditionthen    commandselse     commands    fi

The condition is set to execute then statement, otherwise else statement.

The test command can only judge three types of conditions:

    • Numerical comparison
    • string comparison
    • File comparison

For example: if test usage:

[Email protected] ~]# cat wwww.sh if test $[5<3]        '5 less than 3'else'  5 greater than 3'fi

Operation Result:

[[email protected] ~]#./Wwww.sh5 less than 3

Numerical comparison
Compare Description
N1-eq N2 Determine if N1 equals N2
N1-ge N2 Determine if N1 is greater than or equal to N2
N1-GT N2 Determine if N1 is greater than N2
N1-le N2 Determine if N1 is less than or equal to N2
N1-lt N2 Determine if N1 is less than N2
N1-ne N2 Determine if N1 is not equal to N2

Special reminder: The above table does not need you to remember, below the command line, executes the man test to see these. The following pair is the same as the other two comparisons

#!/bin/bashnum1=num2=if test $num 1-eq $num 2then    Echo NUM1 equals num2else    echo num2 not equal to Num2fi

 

Good standard mathematical comparison symbol can not be used, must write this form of text? Does it feel awkward?
No hurry, there are alternatives:

Use double brackets

The double-brace command allows you to use advanced mathematical expressions in the comparison process. The key is to use double brackets, we can use mathematical comparison of symbols (= = =, greater than, less than <, etc. can be used).
How to use:

expression ))

Note: Spaces are required on both sides of the parentheses

#!/bin/bashnum1=num2=if ((Num1 >    num2)) Then " num1 > Num2 " Else "Num2<= num2"         

 
string comparison
Compare Description
STR1 = str2 Determine if STR1 is the same as str2
Str1! = str2 Determine if STR1 is not the same as str2
STR1 < STR2 Determine if STR1 is smaller than STR2 (based on ASCII)
str1 > STR2 Determine if STR1 is larger than STR2 (based on ASCII)
-N str1 Determine if the length of the str1 is not 0
-Z str1 Determine if the length of the str1 is 0

Program apes, if you want to scold them, let them go. I was cursed anyway.

The test command and the test expression use standard mathematical comparison symbols to represent string comparisons, and text codes to represent numeric comparisons. This is different than other languages.

#!/bin/bashvar1=testvar2=Testif test $var 1 = $str 2then    echo equal  else     echo Not equal fi

 

Note that when you use a greater than (>) or less than (<) symbol, you need to escape (\>) (\<), otherwise the two symbols are not redirected (as discussed later in this article).

Spit Groove mode on: I want to use a comparison symbol, but also to escape, very painful design!

Don't panic, the big strokes are usually in the back:

Use both brackets

The two-side brackets command provides advanced features for string comparisons. It not only solves a series of problems with the use of test, but also provides some advanced usage that the test command does not have. The format of the two-bracket command is as follows:

[[ expression ]]    

Note that some shells may not support this type of notation. But bash is perfectly supportive. Note that there are spaces on both sides of the brackets in the above notation.

#!/bin/bashvar1=testvar2=Testif [[$test < $test 2]]then    ]  test1 < test2"else    "test1 >= test2 " fi   

This is finally not escaped.

File comparison

The comparison of the files, in fact, is similar to the above, all with the test command. As space is limited, I don't write much here. You can see the specific usage using the Man Test command.

Case statement

In the case of using the If-then-else statement, if you encounter a lot of conditions, the following:

#!/bin/Bashnum=3if($num = =1) then echo"Num=1"elif (($num==2) then echo"num=2"elif (($num==3) then echo"num=3"elif (($num==4) then echo"num=4"fi

If there are more conditions, does it look like a lot of things?
At this point, there is actually an alternative, which is to use case.

 Case inch | pattern2) commands1;; PATTERN3) commands2;; default commands;; Esac

 

Replace the above code with case:

#!/bin/Bash
Num=3 Case$numinch1) echo"Num=1";;2) echo"num=2";;3) echo"num=3";;4) echo"num=4";;*) echo"Defaul";; Esac

Summary

This article mainly tells the conditional statement. The most important difference between a conditional statement in a shell and another programming language is that the conditional statement is followed by a command, not a Boolean value, which is determined by the execution of the exit status code from the command to decide whether to enter the then statement. This needs to be borne in mind.

Shell Programming (iii)

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.