Just learn Linux process control statements if, for

If, for, while, and case are four kinds of flow control statements to learn to write more difficult and more powerful Shell scripts.
Double quotes ("): Double quotes are used to create a string containing text. Text inside double quotes can contain variables and the expansion of special characters, such as the escape character (\), command substitution (command or $(command)) , and a reference to the variable ($variable).

name="John"
echo "My name is $name."

The output will be: My name is John.

Single quotes ('): Single quotes are used to create a string containing text, but it treats all characters inside as literals without any expansion or replacement. Single quotes preserve the literal meaning of the string, including special characters, variable and command substitutions, etc. will not be executed or expanded.

name="John"
echo 'My name is $name.'

The output will be: My name is $name.

As you can see, the variable $name inside the single quotes has not been replaced with the actual value.

if conditional test statement

insert image description here
The following uses a single-branch if conditional statement to determine whether the /media/cdrom directory exists, and if it does not exist, create this directory, otherwise, end the conditional judgment and the execution of the entire Shell script.

vim mkcdrom.sh

#! /bin/bash
DIR = "/media/cdrom"
if [ ! -d $DIR ]
then
	mkdir -p $DIR
fi

Since Chapter 5 explains user identity and authority, here we continue to use the method of "bash script name" to execute the script. Under normal circumstances, there is no output information after the script file is successfully executed, but you can use the ls command to verify whether the /media/cdrom directory has been successfully created:

bash mkcdrom.sh
ls -ld /media/cdrom

The double-branch structure of the if conditional statement is composed of if, then, else, and fi keywords. It performs a condition matching judgment. If it matches the condition, it will execute the corresponding preset command; otherwise, it will execute the preset when it does not match. Command, equivalent to colloquial "if...then...or...then...". The double-branch structure of the if conditional statement is also a very simple judgment structure. The syntax format is shown in the figure. The
insert image description here
following uses the double-branch if conditional statement to verify whether a certain host is online, and then according to the result of the return value, either display the online information of the host , or display the information that the host is not online. The script here mainly uses the ping command to test the network connectivity with the other host, and the ping command in the Linux system does not end after 4 attempts like Windows, so in order to prevent the user from waiting too long, it needs to be specified by the -c parameter The number of attempts, and use the -i parameter to define the sending interval of each packet, and the -W parameter to define the wait timeout.

vim chkhost.sh
#! /bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then 
	echo "Host $1 is On-line"
else 
	echo "Host $1 is Off-line"
fi

Therefore, the integer comparison operator can be used to judge whether the $? variable is 0, so as to know the final judgment of that statement. The IP address of the server here is 192.168.10.10, let's verify the effect of the script:

bash chkhost.sh 192.168.10.10
bash chkhost.sh 192.168.10.20

The multi-branch structure of the if conditional statement is composed of if, then, else, elif, and fi keywords. It performs multiple condition matching judgments. Any item in the multiple judgments will execute the corresponding preset command after the matching is successful. Equivalent to colloquial "if...then...if...then...". The multi-branch structure of the if conditional statement is the most commonly used conditional judgment structure in work. Although it is relatively complex, it is more flexible. The syntax format is shown in the figure.

The multi-branch if conditional statement is used below to determine which grade range the score entered by the user is in, and then output prompt information such as Excellent, Pass, and Fail. In the Linux system, read is a command used to read user input information, which can assign the received user input information to the specified variable later, and the -p parameter is used to display some prompt information to the user.
insert image description here
In the following script example, only when the score entered by the user is greater than or equal to 85 and less than or equal to 100, the word Excellent will be output; if the score does not meet this condition (that is, the match is unsuccessful), continue to judge whether the score is greater than or equal to 70 and less than or equal to 84 points, if yes, then output the word Pass; if both fail (that is, the two matching operations failed), then output the word Fail:

vim chkscore.sh
#!/bin/bash
read -p "Enter your score (0-100):" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ] ; then
		echo "$GRADE is Excellent"
elif [ $GRADE -ge 70 ] && [ $GRADE -le 84 ] ; then
		echo "$FREADE is pass"
else
	echo "$GRADE is Fail"
fi

bash chkscore.sh
88
bash chkscore.sh
80

Execute the script below. When the user enters scores of 30 and 200, the results are as follows:

bash chkscore.sh
30
bash chkscore.sh
200

for conditional loop statement

The for loop statement allows the script to read multiple messages at once, and then perform operations on the messages one by one. When the data to be processed has a range, the use of the for loop statement is perfect. The syntax format of the for loop statement is shown in the figure.
insert image description hereThe following uses the for loop statement to read multiple user names from the list file, and then create user accounts and set passwords for them one by one. First create a list file users.txt of user names, with each user name on a separate line. Readers can decide the specific user name and number by themselves:

vim users.txt
andy
barry
carl
duck
eric
george

Next write the shell script addusers.sh. Use the read command in the script to read the password value entered by the user, then assign it to the PASSWD variable, and display a prompt message to the user through the -p parameter, telling the user that the content being entered will be used as the account password. After executing the script, it will automatically use all the user names obtained from the list file users.txt, and then use the "id user name" command one by one to view the user information, and use $? to judge whether the command is executed successfully, or It is to judge whether the user already exists.

vim addusers.sh
#!/bin/bash
read -p "Enter The Users Password :" PASSWD
for UNAME in `cat users.txt`
do
	id $UNAME &> /dev/null
	if [ $? -eq 0 ]
	then 
		echo "UNAME, Already exists"
	else 
		useradd $UNAME &> /dev/null
		echo "$PASSWD" | passwd --stdin $UNAME &> /dev/null
		echo "$UNAME, Create success"
	fi
done

/dev/null is a file called a Linux black hole. Redirecting output information to this file is equivalent to deleting data (similar to a trash can without recycling function), which can keep the user's screen window clean.

In Linux systems, /etc/passwd is a file used to save user account information. If you want to confirm whether this script has successfully created user accounts, you can open this file to see if there are these newly created user information.

bash addusers.sh
tail -6 /etc/passwd

Try having a script that automatically reads a list of hosts from text, and then automatically tests those hosts one by one to see if they are online.
First create a host list file ipaddrs.txt:

vim ipaddrs.txt
vim CheckHosts.sh
#!/bin/bash
HLTST=$(cat~/ipaddrs.txt)
for IP in $HLIST
do
	ping -c 3 -i 0.2 -W 3 $IP &> /dev/null
	if [ $? -eq 0 ]
	then 
		echo "Host $IP is On-line"
	else 
		echo "Host $IP is Off-line"
	fi
done

./CheckHosts.sh

おすすめ

転載: blog.csdn.net/AdamCY888/article/details/131301578