The use of the-if flow control statement and the FOR Loop statement for the 1-23-shell script

Source: Internet
Author: User

Outline:

1. Logical Judgment

2. If flow control statement

3. For loop control statement

----------------------------------------------

Before you begin, let's look at the logical judgment symbol:

&& and,| | Or,! Non -

A && B must be set up at the same time to pass judgment

---> Judgment process: First execute a to determine whether it is established, if it is established, continue to execute B, determine whether it is established

---> If not, it ends directly and no longer executes B

A | | b A, B has a set up, can be judged by

! A if A is not established, then by judging

----------------------------------------------

----------------------------------------------

when the condition is judged, that side compares the value or the string, which is what we will use some parameters and symbols, as follows :

Compare values:

Equals--->–eq.

Not equal to--->–ne

Less than--->–lt

Greater than--->–gt

Less than or equal to--->–le

Greater than or equal to--->–ge

Some English words: Help memory

Equal equals, not equal, less than, great than

Compare strings:

= equals, = = equals, same =,! = is not equal, > is greater than, < less than,-Z string is empty,-n string is not null

Note: in the [] structure,< and > need to use escape symbols, such as

Combat 1: Judging the current system language environment

[Email protected] 02]# echo $LANG
en_US. UTF-8
[Email protected] 02]# echo $LANG | Awk-f. ' {print '} '
en_US
[Email protected] 02]# vim lang.sh
[Email protected] 02]# sh-x lang.sh
+ + echo en_US. UTF-8
+ + awk-f. ' {print '} '
+ Language=en_us
+ ' [' en_US = en_US '] '
+ Echo ' The Default Language is 中文版. '
The Default Language is 中文版.
[email protected] 02]# cat lang.sh
#!/bin/bash
# judged if the System Default Language is 中文版

language=$ (echo $LANG | awk-f. ' {print $} ')

If
[$language = ' en_US ']
Then echo "The Default Language is 中文版."
else echo "You are wrong!"
Fi

[Email protected] 02]#


----------------------------------------------

If Process Control statement

There are three ways to use the IF statement:

The format is as follows:

Single branch:

If condition judgment statement

Then execute the statement

Fi

Dual Branch:

If condition judgment statement

Then execute the statement

Else EXECUTE statement

Fi

Multi-branch:

If condition judgment statement

Then execute the statement

Else EXECUTE statement

Fi

##################################
Combat 1:if Single Branch---> Application

The source code is as follows:

#!/bin/bash
# if
# Then
# fi

if [!-d/root/cdrom]
Then echo "/root/cdrom was not exist!"
Fi

##################################
actual combat 2:if Dual Branch Application--->pinghost.sh
Ping-c 3-i 0.2-w 3 192.168.0.1

-C Send the number of packets

-I packet send interval time, default unit: seconds (s)

-W wait Time exceeded return failure

The source code is as follows:

#!/bin/bash
# Ping a given host and print the host status

Ping-c 3-i 0.2-w 3 >>/dev/null #-c count-i-W Wait
If [$?-eq 0]
Then echo "The host was up."
else echo "The host is down."
Fi

##################################

actual combat 3:if Multi-branch Application---> Judging numerical interval num_where.sh

The source code is as follows:

#!/bin/bash
# judged the input score

Read-p "Input you Score (0-100):" num

If [$num-gt] && [$num-lt 100]
Then echo "great! Good good study!! "
else echo "Day Day up!"
Fi

##################################

Actual combat 4:if Nested use

write scripts to monitor service run status ,
After the startup fails, save the log and restart the service.
Fail again, prompt to restart the host

The source code is as follows:

#!/bin/bash

Systemctl Status $ >>/var/log/ser.log

If [$?-eq 0]
Then echo "The $ is running."
else echo "The $ is dead."
Systemctl Start $ >>/dev/null
If [$?-eq 0]
Then echo "Reboot finish!"
Systemctl Restart $
else echo "warnning you to Reboot your server!"
Fi
Fi

##################################
Combat 5: Query kernel version, and output information

The source code is as follows;

#!/bin/bash
# Search the major version of System, and print info.

prime=$ (Uname-r | awk-f. ' {print $} ')

If [$prime-GT 2]
Then echo, "the major version of System is $prime."
elif [$prime-lt 1]
Then echo "The System was too low."
else echo "failed!"
Fi

----------------------------------------------

For loop control statements

Usage:

For variable name in variable traversal list

Do

Looping statements

Done #循环结束表示

##################################

Combat: User Management (bulk add users)

Method One:

Operating Environment:

Output Result:

To delete a user in bulk:

Method One optimization:

We found that in a batch of methods to add the user is, when the user does not exist, there will be an error message. Review the following procedures:

Sh–x for01_useradd.sh

After entering the loop, we will first look for/etc/passwd, if there is already a user $user,

However, in the process of operation, we found that when the user does not exist when the user_a value is empty, the judgment condition will be less a comparison value, and the result of the judgment condition becomes: [= Xiaogan], this is the system will error!

To avoid system errors, we can use the-Z or-n option to determine if the user_a variable is empty.

The results of the implementation are as follows:

Method Two: We can also take another way to bulk add users

The source code of each method is as follows:

Method One:

#useradd. Sh

#!/bin/bash
userlist=$ (Cat user.list)


For user in $userlist
Do
user_a=$ (grep-w "$user"/etc/passwd | awk-f: ' {print $} ')
If
[$user _a = $user]
Then
echo "The user $user is already exist."
Else
Useradd $user #2 >>/dev/null
echo "User $user is added."
Fi
Done

###########

#userdel. Sh

#!/bin/bash
userlist=$ (Cat user.list)

For user in $userlist
Do
Userdel-r $user 2>>/dev/null
If [$? = 0]
Then
echo "The user $user is deleted!"
Fi
Done

Optimization:

#usera dd.sh

#!/bin/bash
userlist=$ (Cat user.list)


For user in $userlist
Do
user_a=$ (grep-w "$user"/etc/passwd | awk-f: ' {print $} ')
If
# [$user _a = $user]
[! $user _a-z] && [$user _a = $user]
# to determine whether user_a are empty, not empty on to continue
Then
echo "The user $user is already exist."
Else
Useradd $user #2 >>/dev/null
echo "User $user is added."
Fi
Done

Method Two:

#new useradd.sh

#!/bin/bash
# Batch Add user by scripts
# The New method

userlist=$ (Cat user.list)

For user in $userlist
Do
Useradd $user 2>>/dev/null
If
[$?-eq 0]
Then
echo "123456" | passwd--stdin $user >>/dev/null
echo "Useradd success!"
Else
echo "The user $user is already exists."
Fi
Done

##################################

Combat: Ping.sh #批量测试IP地址是否连通


The source code is as follows:

#!/bin/bash

ip_list=$ (Cat ip.list)

For IP in $ip _list
Do
Ping-w 3-c 3-i 0.2 $ip >>/dev/null
If [$?-eq 0]
Then echo "The $ip was up."
else echo "The $ip is down."
Fi
Done

The use of the-if flow control statement and the FOR Loop statement for the 1-23-shell script

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.