Linux should learn this way-conditional statements

for conditional loop statement

The for loop statement allows the script to read multiple information at once, and then manipulate the information one by one. When the data to be processed has a range, the for loop statement is more suitable, and execute the Shell script Example.sh that creates users in batches. After entering the password set for the account, the script will automatically check and create these accounts. Since the redundant information has been transferred to the /dev/null black hole file through the output redirection character

[root@myserver ~]# cat users.txt 
ndy
barry
carl
duke
eric
george
[root@myserver ~]# cat Example.sh 
#!/bin/bash
 read -p "Enter The Users Password : " PASSWD
 for UNAME in `cat users.txt`
 do
	 if [ $? -eq 0 ]
	 then
		 echo "Already exists"
	 else
		 useradd $UNAME &> /dev/null
		 echo "$PASSWD" | passwd --stdin $UNAME &> /dev/null
		 if [ $? -eq 0 ]
		 then
			 echo "$UNAME , Create success"
		 else
			 echo "$UNAME , Create failure"
		 fi
	 fi
 done
[root@myserver ~]# 

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

[root@myserver ~]# sh Example.sh 
Enter The Users Password : linuxprobe
ndy , Create success
barry , Create success
carl , Create success
duke , Create success
eric , Create success
george , Create success
[root@myserver ~]# 

Exercise: count down 5 seconds

[root@myserver ~]# cat example1.sh 
#!/bin/bash
echo "准备倒数5秒:"
for i in $(seq 5 -1 1)
do
	  echo -en "$i";sleep 1
  done
  echo -e "开始"
[root@myserver ~]# sh example1.sh 
准备倒数5秒:
54321开始
[root@myserver ~]# 

while conditional loop statement

The while conditional loop statement is a statement that allows the script to repeatedly execute commands based on certain conditions. Its loop structure is often not sure the final number of executions before it is executed, which is completely different from the use of a for loop statement that has a target and a range. Scenes. The while loop statement determines whether to continue executing the command by judging the true or false of the condition test. If the condition is true, it will continue to execute, and if it is false, it will end the loop. The grammatical format of the while statement is shown in Figure 4-21.Chapter 4 Vim Editor and Shell Command Script.  Chapter 4 Vim Editor and Shell Command Script.

Figure 4-21 The syntax format of the while loop statement

Next, use the multi-branch if conditional test statement and the while conditional loop statement to write a script Guess.sh that is used to guess the magnitude of the value. The script uses the $RANDOM variable to retrieve a random value (range 0~32767), performs the remainder operation on this random number to 1000, and uses the expr command to obtain the result, and then uses this value to communicate with the user through the read command The entered value is compared and judged. This judgment sentence is divided into three situations, which are to judge whether the value entered by the user is equal to, greater than or less than the value obtained by using the expr command. At present, these contents are not the focus. What we are currently paying attention to is that the condition test in the while conditional loop statement is always true, so the judgment statement will be executed indefinitely until the value entered by the user is equal to the value obtained by the expr command. Run the exit 0 command after being equal to terminate the execution of the script

[root@myserver ~]# vim Guess.sh

#!/bin/bash
PRICE=$(expr $RANDOM % 1000)
TIMES=0
echo "商品实际价格为0-999之间,猜猜看是多少?"
while true
do
        read -p "请输入您猜测的价格数目:" INT
        let TIMES++
        if [ $INT -eq $PRICE ] ; then
                echo "恭喜您答对了,实际价格是 $PRICE"
                echo "您总共猜测了 $TIMES 次"
                exit 0
        elif [ $INT -gt $PRICE ] ; then
                echo "太高了!"
        else
                echo "太低了!"
        fi
done

[root@myserver ~]# sh Guess.sh 
商品实际价格为0-999之间,猜猜看是多少?
请输入您猜测的价格数目:600
太高了!
请输入您猜测的价格数目:500
太高了!
请输入您猜测的价格数目:300
太低了!
请输入您猜测的价格数目:450
太低了!
请输入您猜测的价格数目:480
太高了!
请输入您猜测的价格数目:470
太高了!
请输入您猜测的价格数目:460
太高了!
请输入您猜测的价格数目:455    
太低了!
请输入您猜测的价格数目:456
恭喜您答对了,实际价格是 456
您总共猜测了 9 次
[root@myserver ~]# 

The shell uses the while loop to print out the triangle

[root@myserver ~]# cat example2.sh
#!/bin/sh
i=1
while [ $i -le 10 ] ; do
	j=1
	while [ $j -le $((10-$i)) ] ; do
		echo -n ' '
		j=$(($j+1))
	done

	j=1
	while [ $j -le $((2*$i-1)) ] ; do
		echo -n x
		j=$(($j+1))
	done
	echo
	i=$(($i+1))
done
exit 0
[root@myserver ~]# sh !$
sh example2.sh
         x
        xxx
       xxxxx
      xxxxxxx
     xxxxxxxxx
    xxxxxxxxxxx
   xxxxxxxxxxxxx
  xxxxxxxxxxxxxxx
 xxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxx
[root@myserver ~]# 

case conditional test statement

If you have studied the C language before, you will surely smile when you see the title of this section "Isn't this a switch statement!" Yes, the function of the case conditional test statement and the switch statement are very similar! The case statement is to match data in multiple ranges. If the match is successful, the relevant command is executed and the entire condition test is ended; if the data is not in the listed range, the default command defined in the asterisk (*) will be executed . The grammatical structure of the case statement is shown in Figure 4-22.

Chapter 4 Vim Editor and Shell Command Script.  Chapter 4 Vim Editor and Shell Command Script.

Figure 4-22 The grammatical structure of the case conditional test statement

There is a fatal weakness in the Guess.sh script introduced above-it can only accept numbers! You can try to enter a letter, and you will find that the script crashes immediately. The reason is that letters cannot be compared with numbers. For example, the proposition "is a greater than or equal to 3" is completely wrong. We must have certain measures to determine the user’s input. When the user’s input is not a number, the script can prompt it to avoid crashing.

By combining case conditional test statements and wildcards in the script (see Chapter 3 for details), this requirement can be fully met. Next, we write the script Checkkeys.sh, prompt the user to enter a character and assign it to the variable KEY, and then show the user whether the value is a letter, number or other character according to the value of the variable KEY.

[root@myserver ~]# cat Checkkeys.sh 
#!/bin/bash
read -p "请输入一个字符,并按Enter键确认:" KEY
case "$KEY" in
	[a-z]|[A-Z])
		echo "您输入的是 字母。"
		;;
	[0-9])
		echo "您输入的是 数字。"
		;;
	*)
		echo "您输入的是 空格、功能键或其他控制字符。"
esac
[root@myserver ~]# sh Checkkeys.sh 
请输入一个字符,并按Enter键确认:3
您输入的是 数字。

Exercise

[root@myserver ~]# cat  example3.sh
#!/bin/bash
printf "Input integer number: "
read num
case $num in
    1)
        echo "Monday"
        ;;
    2)
        echo "Tuesday"
        ;;
    3)
        echo "Wednesday"
        ;;
    4)
        echo "Thursday"
        ;;
    5)
        echo "Friday"
        ;;
    6)
        echo "Saturday"
        ;;
    7)
        echo "Sunday"
        ;;
    *)
        echo "error"
esac
[root@myserver ~]# sh !$
sh example3.sh
Input integer number: 5
Friday

Scheduled task service program

Experienced system operation and maintenance engineers can enable Linux to automatically enable or stop certain services or commands at a specified time period without human intervention, thereby realizing the automation of operation and maintenance. Although we now have a powerful script program to perform some batch processing work, but if you still need to hit the keyboard enter key to execute this script program at two o'clock in the morning every day, this is simply too painful (of course, also You can train your kitten to press the Enter key in the middle of the night). Next, Mr. Liu Dun will explain to everyone how to set up the scheduled task service of the server, and hand over the periodic and regular work to the system to complete automatically.

One-time scheduled tasks are executed only once, and are generally used to meet temporary work requirements. We can use the at command to achieve this function, just write it in the form of "at time". If you want to view a one-time scheduled task that has been set but not yet executed, you can use the "at -l" command; if you want to delete it, you can use the "atrm task number". When using the at command to set up a one-time scheduled task, the interactive method is used by default. For example, use the following command to set the system to automatically restart the website service at 23:30 tonight

[root@linuxprobe ~]# at 23:30
at > systemctl restart httpd
at > 此处请同时按下Ctrl+d来结束编写计划任务
job 3 at Mon Apr 27 23:30:00 2015
[root@linuxprobe ~]# at -l
3 Mon Apr 27 23:30:00 2016 a root

Before officially deploying the planned task, please read the mantra "Minute, hour, day, month, and week order" to Teacher Liu Dun. This is the parameter format for setting tasks using the crond service (see Table 4-6 for the format). It should be noted that if some fields are not set, you need to use an asterisk ( * ) to occupy the position, as shown in Figure 4-23.Chapter 4 Vim Editor and Shell Command Script.  Chapter 4 Vim Editor and Shell Command Script.

Figure 4-23 Use crond to set the parameter format of the task

You can also refer to the website to adjust your own timing tasks  https://tool.lu/crontab/

Suppose that every Monday, Wednesday, and Friday at 3:25 in the morning, you need to use the tar command to package the data directory of a certain website as a backup file. We can use the crontab -e command to create a scheduled task. There is no need to use the -u parameter to create a scheduled task for yourself. The specific parameters to achieve the effect are as shown in the crontab -l command result:

[root@myserver ~]# crontab -l
25 3 * * 1,3,5 /usr/bin/tar -czvf backup.tar.gz /home/wwwroot
[root@myserver ~]# crontab -e

25 3 * * 1,3,5 /usr/bin/tar -czvf backup.tar.gz /home/wwwroot

User identity and capabilities

 

The administrator UID is 0: the administrator user of the system.

System user UID is 1~999: In order to avoid hackers from escalating rights to the entire server due to a vulnerability in a certain service program, the default service program will be run by an independent system user to effectively control the scope of damage. Common user UID starts from 1000: it is a user created by the administrator for daily work

 useradd command

The useradd command is used to create a new user, the format is "useradd [option] username".

You can use the useradd command to create a user account. When using this command to create a user account, the default user home directory will be stored in the /home directory, the default Shell interpreter is /bin/bash, and a basic user group with the same name as the user will be created by default

-c<备注>  加上备注文字。备注文字会保存在passwd的备注栏位中。
-d<登入目录>  指定用户登入时的起始目录。
-D  变更预设值.
-e<有效期限>  指定帐号的有效期限。
-f<缓冲天数>  指定在密码过期后多少天即关闭该帐号。
-g<群组>  指定用户所属的群组。
-G<群组>  指定用户所属的附加群组。
-m  自动建立用户的登入目录。
-M  不要自动建立用户的登入目录。
-n  取消建立以用户名称为名的群组.
-r  建立系统帐号。
-s<shell>   指定用户登入后所使用的shell。
-u<uid>  指定用户ID。

Add general user

[root@myserver ~]# id yhd
uid=1007(yhd) gid=1007(yhd) groups=1007(yhd)

Add a system user

[root@myserver ~]# useradd -r yang
[root@myserver ~]# id yang
uid=976(yang) gid=974(yang) groups=974(yang)
[root@myserver ~]# 

Specify the home directory for the newly added user

[root@myserver ~]# useradd -d /home/gaga xiaxia
[root@myserver ~]# tree /home
/home
├── barry
├── carl
├── duke
├── eric
├── gaga
├── george
├── linuxprobe
│   ├── Desktop
│   ├── Documents
│   ├── Downloads
│   ├── Music
│   ├── Pictures
│   ├── Public
│   ├── Templates
│   └── Videos
├── ndy
└── yhd

17 directories, 0 files
[root@myserver ~]# 

 Create users and make IDs

[root@myserver ~]# useradd caocao -u 544
[root@myserver ~]# id caocao
uid=544(caocao) gid=1011(caocao) groups=1011(caocao)
[root@myserver ~]# 

Below we create an ordinary user and specify the path of the home directory, the user's UID, and the Shell interpreter. In the following commands, please pay attention to /sbin/nologin, which is a member of the terminal interpreter, which is very different from the Bash interpreter. Once the user's interpreter is set to nologin, it means that the user cannot log in to the system: 

[root@myserver ~]# useradd -d /home/linux -u 8888 -s /sbin/nologin laoliu
[root@myserver ~]# id laoliu
uid=8888(laoliu) gid=8888(laoliu) groups=8888(laoliu)
[root@myserver ~]# 

 

 groupadd command

The groupadd command is used to create a user group, the format is "groupadd [option] group name".

In order to be able to assign the permissions of each user in the system more efficiently, several users are often added to the same group in the work, so that the permissions can be arranged uniformly for a type of user. The steps to create a user group are very simple

-g:指定新建工作组的 id;
-r:创建系统工作组,系统工作组的组ID小于 500;
-K:覆盖配置文件 "/ect/login.defs";
-o:允许添加组 ID 号不唯一的工作组。
-f,--force: 如果指定的组已经存在,此选项将失明了仅以成功状态退出。当与 -g 一起使用,并且指定的GID_MIN已经存在时,选择另一个唯一的GID(即-g关闭)。

 usermod command

The usermod command is used to modify the attributes of a user, and the format is "usermod [option] username".

-c<备注>  修改用户帐号的备注文字。
-d登入目录>  修改用户登入时的目录。
-e<有效期限>  修改帐号的有效期限。
-f<缓冲天数>  修改在密码过期后多少天即关闭该帐号。
-g<群组>  修改用户所属的群组。
-G<群组>  修改用户所属的附加群组。
-l<帐号名称>  修改用户帐号名称。
-L  锁定用户密码,使密码无效。
-s<shell>  修改用户登入后所使用的shell。
-u<uid>  修改用户ID。
-U  解除密码锁定。

  passwd command

The passwd command is used to modify user password, expiration time, authentication information, etc. The format is "passwd [option] [user name]"

-l	锁定用户,禁止其登录
-u	解除锁定,允许用户登录
--stdin	允许通过标准输入修改用户密码,如echo "NewPassWord" | passwd --stdin Username
-d	使该用户可用空密码登录系统
-e	强制用户在下次登录时修改密码
-S	显示用户的密码是否被锁定,以及密码所采用的加密算法名称

Modify the common user password and root password

[root@myserver ~]# passwd yhd
Changing password for user yhd.
New password: 
BAD PASSWORD: The password is a palindrome
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@myserver ~]# passwd
Changing password for user root.
New password: 
BAD PASSWORD: The password is a palindrome
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@myserver ~]# 

The passwd command prohibits the user from logging in to the system (lock user ---> view user status --> unlock user ---> view user status)

[root@myserver ~]# passwd -l yhd
Locking password for user yhd.
passwd: Success
[root@myserver ~]# passwd -S yhd
yhd LK 2021-01-15 0 99999 7 -1 (Password locked.)
[root@myserver ~]# passwd -u yhd
Unlocking password for user yhd.
passwd: Success
[root@myserver ~]# passwd -S yhd
yhd PS 2021-01-15 0 99999 7 -1 (Password set, SHA512 crypt.)
[root@myserver ~]# 

 userdel command

The userdel command is used to delete a user, the format is "userdel [option] username"

-f	强制删除用户
-r	同时删除用户及用户家目录
[root@myserver ~]# tail -f /etc/passwd
duke:x:1004:1004::/home/duke:/bin/bash
eric:x:1005:1005::/home/eric:/bin/bash
george:x:1006:1006::/home/george:/bin/bash
yhd:x:1007:1007::/home/yhd:/bin/bash
yang:x:976:974::/home/yang:/bin/bash
gaga:x:1008:1008::/yang/hua:/bin/bash
pipi:x:1009:1009::/yang/gaga:/bin/bash
xiaxia:x:1010:1010::/home/gaga:/bin/bash
caocao:x:544:1011::/home/caocao:/bin/bash
laoliu:x:8888:8888::/home/linux:/sbin/nologin
^C
[root@myserver ~]# userdel -r pipi
[root@myserver ~]# tail -f /etc/passwd
carl:x:1003:1003::/home/carl:/bin/bash
duke:x:1004:1004::/home/duke:/bin/bash
eric:x:1005:1005::/home/eric:/bin/bash
george:x:1006:1006::/home/george:/bin/bash
yhd:x:1007:1007::/home/yhd:/bin/bash
yang:x:976:974::/home/yang:/bin/bash
gaga:x:1008:1008::/yang/hua:/bin/bash
xiaxia:x:1010:1010::/home/gaga:/bin/bash
caocao:x:544:1011::/home/caocao:/bin/bash
laoliu:x:8888:8888::/home/linux:/sbin/nologin
^C
[root@myserver ~]# 

 

Guess you like

Origin blog.csdn.net/yanghuadong_1992/article/details/112689481