Shell script conditional control and loop statement _linux Shell

Source: Internet
Author: User
Tags case statement

Conditional judgment: If statement

Syntax format:

If [expression]
then
Statement (s) to was executed if expression is true
fi

Note: There must be a space between the expression and the square brackets ([]), otherwise there will be a syntax error.

The IF statement determines which branch to execute through the relational operator to determine the true or false of an expression. The Shell has three kinds of if ... else statements:

If ... fi statement elif ... else ... fi statement if ... other ... a. A..

Example:

#!/bin/bash/
a=10
b=20
if [$a = = $b]
then 
echo "A is equal to B"
elif [$a-gt $b]
t Hen
echo "A is greater to B"
else
echo "A are less to B"
fi

The IF ... else statement can also be written as a line and run as a command:

a=10;b=20;if [$a = = $b];then echo "A is equal to B"; else echo "A's not equal to B"; fi;

The IF ... Else statement is also often used in conjunction with the Test command, which acts as above:

#!/bin/bash/
a=10
b=20
if test $a = = = $b 
then 
echo "A is equal to B"
else
echo "A isn't" equal to B "
fi

Branch control: Case statement

Case ... Esac with the switch in other languages ... case statements are similar to a multiple branching selection structure.

Example:

#!/bin/bash/
grade= "B" Case
$grade in 
"A") echo "Very good!";;
B ") echo" good! ";;
" C ") echo" Come on! ";;
*) 
echo "You must try!"
echo "sorry!";;
Esac

Convert to C language is:

#include <stdio.h>
int main () {
char grade = ' B ';
Switch (grade) {case
' A ': printf ("Very good!"); break;
Case ' B ': printf ("Very good!"); break;
Case ' C ': printf ("Very good!"); break;
Default: 
printf ("You must try!");
printf ("sorry!");
break;
return 0;
}

It's easy to understand by contrast. Very similar, but the format is not the same.

It is to be noted that:

After the value must be keyword in, each pattern must end with a closing parenthesis. The value can be a variable or a constant. When a match finds that a value conforms to a pattern, all commands begin to execute until;;; Similar to a break in other languages, it means jumping to the end of the entire case statement.

The value will detect each pattern that matches. Once the pattern matches, the corresponding command after the match pattern is executed and no more mode continues. If there is no matching pattern, use the asterisk * to capture the value, and then execute the following command.

Let me cite one more example:

#!/bin/bash
option= "${1}" case
${option} in
"-F") file= "${2}"
echo "FILE name is $FILE"
;;
-D ") dir=" ${2} "
echo" DIR name is $DIR "
;;
*) 
echo "' BaseName ${0} ': usage: [F file] | [-D directory] "Exit 1 # Command to come out of the ' program with
status 1
;;
Esac

Run Result:

$./test.sh
test.sh:usage: [f filename] | [-D directory]
. /test.sh-f index.html
File name is index.html

This uses the special variable ${1}, which refers to the first argument to get the command line.

For loop

The Shell's for loop is different from languages such as C and PHP, and is similar to Python. The following is a syntax format:

For variable in list

Do
Command1
command2 ...
CommandN done

Example:

#!/bin/bash/for
value in 1 2 3 4 5
does 
echo "The value is $value"
done

Output:

The value is 1 the ' value is 2 the ' value is 3 the ' value is 4 ' The
value is
5

Characters in the sequential output string:

For str in ' it ' a string '
do
echo $str
done

Run Result:

This is a string

To traverse the files in the directory:

#!/bin/bash for
FILE in *
does
echo $FILE
done

The code above will iterate through all the files in the current directory. Under Linux, you can try a different directory instead.

Traverse File Contents:

City.txt

Beijing
Tianjin
Shanghai
#!/bin/bash
citys= ' cat city.txt ' in
$citys
Echo $city Done

Output:

Beijing
Tianjin
Shanghai

While loop

The code block in do is executed as long as the condition behind it is satisfied.

The format is:

While command
Todo
Statement (s) to was executed if command is true
Done

command completes, control returns to the top of the loop, starting from scratch until the test condition is false.

Example:

#!/bin/bash
c=0;
While [$c-lt 3]
does
echo "Value C is $c"
c= ' expr $c + 1 '
done

Output:

Value C is 0
Value C is 1
Value C is 2

This is because the shell itself does not support arithmetic operations, so the expr command is used to increase the self.

Until cycle

The Until loop executes a series of commands until the condition is true. The Until loop and the while loop are just the opposite of how they are handled. A general while loop is better than a until loop, but at some point it is only a rare case that the until loop is more useful.

Changing the example on the while loop above will achieve the same effect:

#!/bin/bash
c=0;
Until [$c-eq 3]
do
echo "Value c be $c"
c= ' expr $c + 1 '
done

First the statement block in do is run until the until condition is met.

Output:

Value C is 0
Value C is 1
Value C is 2

Jump out of the loop

In the loop, it is sometimes necessary to force out of the loop when the loop end condition is not reached, and like most programming languages, the shell uses break and continue to jump out of the loop.

Break

The break command allows you to jump out of all loops (terminating all loops after execution).

#!/bin/bash
i=0 while
[$i-lt 5]
do
i= ' expr $i + 1 '
if [$i = 3]
then
break
fi
echo-e $i
Done

Run Result:

1
2

In a nested loop, the break command can also be followed by an integer that represents the jump out of the first layer of loops. For example:

Break n

Represents a jump out of the N-tier loop.

Continue

The continue command is similar to the break command, except that it does not jump out of all loops and simply jumps out of the current loop.

#!/bin/bash
i=0 while
[$i-lt 5]
do
i= ' expr $i + 1 '
if [$i = 3]
then
continue Fi
   echo-e $i Done

Run Result:

1
2
4
5

The above content is small to introduce the shell script conditions control and circular statements related knowledge, I hope to help!

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.