Writing shell Management Scripts (ii)

Source: Internet
Author: User
Tags touch command disk usage

8.1 First Test "/etc/vsftpd", "/etc/hosts" is the directory, and through the "$?" Variable view returns a status value to determine the test result.
[Email protected] ~]# [-D/ETC/VSFTPD]
[[email protected] ~]# echo $?
0
[Email protected] ~]# [-d/etc/hosts]
[[email protected] ~]# echo $?
1
[Email protected] ~]# ls-ld/etc/vsftpd/etc/hosts
-rw-r--r--2 root root 187 10-17 13:53/etc/hosts
Drwxr-xr-x 2 root root 4096 10-18 13:31/etc/vsftpd
8.2 Test the existence of "/media/cdrom/server" and its parent directory, or "YES" if present, or output no information.
[[Email protected] ~]# [-e/media/cdrom/server] && echo "YES"
No output indicates that the directory does not exist
[[Email protected] ~]# [-e/media/cdrom] && echo "YES"
Yes//Show Yes indicates that the directory exists
8.3 Log in with a normal user teacher and test if the "/etc/passwd" file has read, write permissions, or "Yes" if it is.
[[Email protected] ~]$ [-W/ETC/PASSWD] && echo "YES"
[[Email protected] ~]$ [-R/ETC/PASSWD] && echo "YES"
YES
8.4 Test if the number of users currently logged on to the system is less than or equal to 10, the output is "yes".
[email protected] ~]$ who | Wc-l
2
[[Email protected] ~]$ [' Who | wc-l '-le] && echo "YES"
YES
8.5 Extract the disk usage of the "/boot" partition and determine if it is more than 95% (for ease of understanding, the procedure is decomposed appropriately).

8.6 Prompts the user to enter a file path and to determine if it is "/etc/inittab", or "yes" if it is.
[Email protected] ~]# Df-ht | grep "/boot" | awk ' {print $6} '
[Email protected] ~]# read-p "localtion:" FilePath
Localtion:/etc/inittab
[[Email protected] ~]# [$FilePath = "/etc/inittab"] && echo "YES"
YES
8.7 If the content of the current environment variable Lang is not "en." US ", the value of the lang variable is output, otherwise there is no output.
[Email protected] ~]# [$LANG! = "en. US "] && echo $LANG
Zh_cn. UTF-8
8.8 Use the touch command to create a new file, test whether its contents are empty, and then test it again after writing to the file.
[email protected] ~]# Touch zero.file
[[Email protected] ~]# [-Z ' cat zero.file '] && echo "YES"
YES//Indicates that the file is an empty file
[[Email protected] ~]# [-Z ' cat zero.file '] && echo "YES"
[Email protected] ~]# echo "Something" > Zero.file
[[Email protected] ~]# [-Z ' cat zero.file '] && echo "YES"
No output indicates that the file is not empty
8.9 test if the current user is teacher, if not teacher.
[Email protected] ~]# echo $USER
Root
[[Email protected] ~]# [$USER = "Teacher"] | | echo "Not teacher"
Not teacher
8.1 Only one of the "/etc/rc.d/rc.local" or "/etc/init.d/rc.local" is a file, then "YES" is displayed, otherwise there is no output.
[[Email protected] ~]# [-f/etc/rc.d/rc.local] | | [-f/etc/init.d/rc.local] && echo "YES"
YES
8.11 Test if the "/etc/profile" file has executable permissions, and if you do not have executable permissions, then prompt "no x mode." The information.
[[Email protected] ~]# [! -X "/etc/profile"] && echo "No x Mode"
No x mode.
8.12 If the current user is root and the shell program used is "/bin/bash", then "YES" is displayed, otherwise there is no output.
[Email protected] ~]# echo $USER $SHELL
Root/bin/bash
[[Email protected] ~]# [$USER = "root"] && [$SHELL = '/bin/bash '] && echo "YES"
YES
8.13 Check the existence of "/var/log/messages" file, if there is the number of rows and output of the statistics file content, otherwise do nothing (reasonable use of variables, can improve writing efficiency).
[Email protected] ~]# vim chklog.sh
#!/bin/bash
Logfile= "/var/log/messages"
If [-f $LogFile]; Then
Wc-l $LogFile
Fi
[Email protected] ~]# sh chklog.sh
1005/var/log/messages
8.14 the user is prompted to specify the path to the backup directory, and if the directory already exists, it is skipped after displaying the prompt, otherwise the directory is created after displaying the appropriate message.
[Email protected] ~]# vim mkbak.sh
#!/bin/bash
Read-p "What's Your backup directory:" Bakdir
If [-D $BakDir]; Then
echo "$BakDir already exist."
Else
echo "$BakDir is not exist, would make it."
mkdir $BakDir
Fi
[Email protected] ~]# sh mkbak.sh
What is your backup directory:/opt/bakroot
/opt/bakroot is not exist, would make it.
[Email protected] ~]# ls-ld/opt/bakroot/
Drwxr-xr-x. 2 root root 4096 11?. 19:30/opt/bakroot/
8.15 count the number of users currently logged in to the system, and determine whether more than three, if the actual number and give a warning message, otherwise list the login user account name and the terminal.
[Email protected] ~]# vim chkuser.sh
#!/bin/bash
Usernum= ' who | Wc-l '
If [$UserNum-gt 3]; Then
echo "Alert, too many login users (total: $UserNum)."
Else
echo "Login Users:"
W.H.O. | awk ' {print $1,$2} '
Fi
[Email protected] ~]# sh chkuser.sh
Login Users:
Root Tty1
Root pts/0
8.16 Check if the Portmap process already exists and output "Portmap service if running" if it already exists. Otherwise, check for the existence of a "/etc/rc.d/init.d/portmap" executable script. exists, start the Portmap service, otherwise prompt "No Portmap script file."
[Email protected] ~]# vim chkportmap.sh
#!/bin/bash
Pgrep Portmap &>/dev/null
If [$?-eq 0]; Then
echo "Portmap service is running."
elif [-X "/etc/rc.d/init.d/portmap"]; Then
Service Portmap Start
Else
echo "No Portmap script file."
Fi
[Email protected] ~]# sh chkportmap.sh
No Portmap script file.
8.17 Monitor the running state of the MYSQLD service every five minutes, append the log information (including time) to the "/var/log/messages" file, and restart the MYSQLD service if the mysqld process is found to be terminated;
[Email protected] ~]# vim chkportmap.sh
#!/bin/bash
Service mysqld Status &>/dev/null
If [$?-ne 0]; Then
echo "At time: ' Date ': MySQL server was down." >>/var/log/messages
Service mysqld Restart
Fi
[Email protected] ~]# sh chkportmap.sh
[Email protected] ~]# tail-1/var/log/messages
At time:2011 Friday, November 18 20:16:31 cst:mysql server is down.
[[email protected] ~]# crontab–e//need to confirm that the Crond service is running
*/5 * * * */root/chkdbsvr.sh
8.18 output three text messages in turn, including "Moring", "Noon", "Evening" string in one day.
[Email protected] ~]# vim showday.sh
#!/bin/bash
For TM in "Morning" "Noon" "Evening"
Do
echo "The $TM of the day."
Done
[Email protected] ~]# sh showday.sh
The morning of the day.
The Noon of the day.
The Evening of the day.
8.19 for system users who use "/bin/bash" as the login shell, check the number of subdirectories or files they have in the "/opt" directory, and if more than 100, list the specific values and corresponding user accounts.
[Email protected] ~]# vim chkfileown.sh

#!/bin/bash
Dir= "/opt"
lmt=100
validusers= ' grep '/bin/bash '/etc/passwd | Cut-d ":"-F 1 '
For UserName in $ValidUsers
Do
Num= ' Find $DIR-user $UserName | Wc-l '
If [$Num-gt $LMT]; Then
echo "$UserName have $Num files."
Fi
Done
[Email protected] ~]# sh chkfileown.sh
[Email protected] ~]# Find-user root | Wc-l
40
8.20 calculates the total amount of space occupied by all profiles in the "/etc" directory in the form of "*.conf".
[Email protected] ~]# vim confsize.sh
#!/bin/bash
sizenums=$ (Ls-l $ (find/etc-type f-a-name *.conf) | awk ' {print $} ')
Total=0
For I in $SizeNums
Do
Total= ' expr $Total + $i '
Done
echo "Total size of conf files: $Total bytes."
[Email protected] ~]# sh confsize.sh
Total size of conf files:813 bytes.
8.21 the user enters an integer greater than 1 from the keyboard, such as 50, and calculates the number of integers from 1 to that count.
[Email protected] ~]# vim sumint.sh
#!/bin/bash
Read-p "Input a number (>1):" Up
I=1
Sum=0
While [$i-le $UP]
Do
sum= ' expr $sum + $i '
i= ' expr $i + 1 '
Done
echo "The sum of 1-$UP is: $sum"
[Email protected] ~]# sh sumint.sh
Input a number (>1): 50
The sum of 1-50 is:1275
8.22 Batch Add 20 system user accounts, the user name is "stu1", "STU2", "Stu3" 、...... "Stu20", each user's initial password is set to "123456".
[Email protected] ~]# vim add20users.sh
#!/bin/bash
I=1
While [$i-le 20]
Do
Useradd stu$i
echo "123456" | passwd--stdin stu$i &>/dev/null
i= ' expr $i + 1 '
Done
[Email protected] ~]# sh add20users.sh
[Email protected] ~]# Tail-2/etc/passwd
Stu19:541:541::/home/stu19:/bin/bash
Stu20:542:542::/home/stu20:/bin/bash
8.23 write a script that deletes the user in bulk, removing the 20 users added in the previous example.
[Email protected] ~]# vim del20users.sh

#!/bin/bash
I=1
While [$i-le 20]
Do
Userdel-r stu$i
i= ' expr $i + 1 '
Done
[Email protected] ~]# sh del20users.sh
[[email protected] ~]# grep "Stu"/etc/passwd//No output means the above user has been removed
8.24 the user enters a character from the keyboard and determines whether the character is a letter, number, or other character, and outputs the appropriate message.
[Email protected] ~]# vim hitkey.sh
#!/bin/bash
Read-p "ress some key, then press Return:" key
Case ' $KEY ' in
[A-z] | [A-z])
echo "It s a letter."
;;
[0-9])
echo "It ' s a digit."
;;
*)
echo "It ' s function keys,spacebar or other keys."
Esac
[Email protected] ~]# sh hitkey.sh
Press some key, then press Return:k
It ' s a letter.
[Email protected] ~]# sh hitkey.sh
Press some key, then press Return:6
It ' s a digit.
[Email protected] ~]# sh hitkey.sh
Presses some key, then press Return: ^[[19~//pressing the F8 key
It ' s function keys,spacebar or other keys.
8.25 Write a shell program, calculate the number of integer values and the individual values that need to be computed are given by the user as command line arguments when executing the script.
[Email protected] ~]# vim sumer.sh
#!/bin/bash
Result=0
While [$#-GT 0]
Do
result= ' expr $Result + $ '
Shift
Done
echo "The sum is: $Result"
[Email protected] ~]# chmod a+x sumer.sh
[Email protected] ~]#./sumer.sh 12 34
The sum is:46
8.26 loop prompts the user to enter a string and saves each input to the temporary file "/tmp/input.txt", when the user enters the "END" string and exits the loop body, and counts the number of rows, words, and bytes in the Input.txt file. Delete the temporary files after the statistics are finished.
[Email protected] ~]# vim inputbrk.sh
#!/bin/bash
While True
Do
Read-p "Input A string:" STR
echo $STR >>/tmp/input.txt
If ["$STR" = "END"]; Then
Break
Fi
Done
Wc/tmp/input.txt
Rm-f/tmp/input.txt
[Email protected] ~]# sh inputbrk.sh
Input a String:wandogn
Input a String:dongdonga
Input a String:end
3 3 22/tmp/input.txt
8.27 Delete stu1~stu20 user accounts in the system, except Stu8, Stu18.
[[Email protected] ~]# sh add20users.sh//execute the script created above to add user
[Email protected] ~]# Tail-2/etc/passwd
Stu19:542:542::/home/stu19:/bin/bash
Stu20:543:543::/home/stu20:/bin/bash
[Email protected] ~]# vim delsome.sh
#!/bin/bash
I=1
While [$i-le 20]
Do
If [$i-eq 8] | | [$i-eq 18]; Then
Let i++
Continue
Fi
Userdel-r stu$i
Let i++
Done
[Email protected] ~]# sh delsome.sh
[[email protected] ~]# grep "Stu"/etc/passwd
Stu8:531:531::/home/stu8:/bin/bash
Stu18:541:541::/home/stu18:/bin/bash
8.28 define a Help function in the script, and when the user enters a script parameter that is not "start" or "Stop", load the function and give the information about the command usage, otherwise give the corresponding hint.
[Email protected] ~]# vim helpfun.sh

#!/bin/bash
Help () {
echo "Usage:" $ "start|stop"
}
Case "$" in
Start
echo "Starting ..."
;;
*)
Help
Esac
[Email protected] ~]# chmod a+x helpfun.sh
[[email protected] ~]#./helpfun.sh start
Starting ...
[Email protected] ~]#/helpfun.sh restart
Usage:./helpfun.sh start|stop
8.29 defines an addition function in the script that calculates the sum of two numbers and calls the function to calculate the sum of 12+34, 56+789, respectively.
[Email protected] ~]# vim adderfun.sh
#!/bin/bash
Adder () {
Echo ' expr + $ '
}
Adder 12 34
Adder 56 789
[Email protected] ~]# sh adderfun.sh
46
845

Writing shell Management Scripts (ii)

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.