Shell Scripting Basics App (ii)

Source: Internet
Author: User
Tags ack first string locale disk usage

In order to make the shell script have a certain "judgment" ability, according to different conditions to accomplish different management tasks. Make the script a certain "smart".
First, condition test operation
File Test Common operations:
-D:: Test for Directory
-E: Test whether the directory or file exists
-F: Test for file
-R: Tests whether the current user has permission to read
-W: Tests whether the current user has permission to write
-X: Test to set permissions that are executable
1. File test: Test whether/media/cdrom exists, 0 indicates existence of this directory, return 1 does not exist.
[Email protected] ~]# [-d/media/cdrom]
[[email protected] ~]# echo $?
0
[Email protected] ~]# ls-d/media/cdrom
/media/cdrom
For a more intuitive display, you can change to the following ways
[[Email protected] ~]# [-d/media/cdrom] && echo "yes"
Yes
[Email protected] ~]#
2, Integer value comparison: Used to determine the number of logged-in users, the number of open processes, disk usage exceeded, and the software version number compliance requirements.
Integer values Common value comparison operation:
-eq: The first number equals the second number
-ne: The first number is not equal to the second number
-GT: The first number is greater than the second number
-LT: The first number is less than the second number
-le: The first number is greater than or equal to the second number
-ge: The first number is greater than or equal to the second number
1) For example: Determine the number of currently logged in users, when more than 5 output "too many"
[email protected] ~]# who
Root tty1 2018-01-30 18:05 (: 0)
Root pts/0 2018-01-30 18:36 (192.168.1.12)
[Email protected] ~]# unum=$ (who | wc-l)
[[Email protected] ~]# [$unum-gt 1] && echo "Too many"
Too many
2) Determine the currently available free memory size, and output a specific value when it is below 1024m.
[[email protected] ~]# freecc=$ (free-m | grep "cache:" | awk ' {print $4} ')
[Email protected] ~]# [$FREECC-lt 1024x768] && echo ${FREECC}MB
[Email protected] ~]# [$FREECC-lt 2048] && echo ${FREECC}MB
[Email protected] ~]# [$FREECC-lt 100000] && Echo ${FREECC}MB
5270MB
3, string comparison: Commonly used to check the user input, the system environment to meet the conditions, and determine whether the user input location parameters meet the requirements.
Characters commonly used character channeling options:
=: The first string is the same as a second string
! =: The first string is not the same as the second string, where "! The symbol indicates the inverse
-Z: Checks if a string is empty, and a variable that is defined or given a null value is treated as an empty string
1) For example: To determine the current locale, when the discovery is not en.us output message "Not en.us"
[Email protected] ~]# echo $LANG//view current locale
Zh_cn. UTF-8
[Email protected] ~]# [$LANG! = "en. US "] && echo" not en. US "//String test result (not equal to)
Not en. US
2) Interactive and simple case
[[email protected] ~]# read-p "Do you want to overwrite the existing file (yes/no)? The ACK
Overwrite existing file? Yes
[[Email protected] ~]# [$ACK = "yes"] && echo "Overlay"
Covered
[[email protected] ~]# read-p "Do you want to overwrite the existing file (yes/no)? The ACK
Overwrite existing file (yes/no)? No
[[Email protected] ~]# [$ACK = "no"] && echo "Do not overwrite"
Do not overwrite
4. Logic test: Determine the dependency between two or more conditions
Common logic test operations are as follows, and are used in different test statements or commands
&&: Logical AND, means "and", the return value of the entire test command is 0 (result) only when the first and the two conditions are true
|| : Logical OR, means "or", as long as one of the two conditions is true, the return value of the entire test command is 0 (the result is set)
! : Logical no, means "no", the return value of the entire test command is only 0 if the specified condition is not true (result is set)
1) For example: To determine if the current Linux kernel version is greater than 2.4, you can do the following:
[[email protected] ~]# munm=$ (uname-r | awk-f. ' {print $} ')//Take the major version number
[[email protected] ~]# snum=$ (uname-r | awk-f. ' {print $} ')//Take this version number
[[Email protected] ~]# [$MUNM-eq 2] && [$snum-gt 4] && echo "OK"
Ok
Second, using the IF condition statement
Function: Better organize the script structure, make the hierarchy clear and easy to understand
1, single-branch if statement

1) For example: Mount the operation of the CD-ROM, first determine whether the mount point directory exists, if not exist, create a new directory
Vi chkmountdir.sh, the contents are as follows:
Vim chkmountdir.sh
#!/bin/bash
Mount_dir= "/media/cdrom"
if [!-D $mount _dir]
Then
Mkdir-p $mount _dir
Fi

2) Determine if the current user is root, if not the error and execute exit 1 exit script (1 means return status value after exiting), and no longer execute other code
[Email protected] ~]# vim chkifroot.sh
#!/bin/bash
If ["$USER"! = "root"]
Then
echo "Cuowu:fei root Yonghu,quanxian Buzu"
Exit 1
Fi
Fdisk-l/DEV/SDA
Execute script:./chkifroot.sh because the currently logged on user is root, so the code after the fi is executed
[Email protected] ~]# chmod +x chkifroot.sh
[Email protected] ~]#./chkifroot.sh

disk/dev/sda:107.4 GB, 107374182400 bytes
255 heads, Sectors/track, 13054 cylinders
Units = Cylinders of 16065 * 8225280 bytes
Sector size (logical/physical): bytes/512 bytes
I/O size (minimum/optimal): bytes/512 bytes
Disk Identifier:0x000e1fe1

Device Boot Start End Blocks Id System
/DEV/SDA1 * 1 512000 Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2 13055 104344576 8e Linux LVM
2, dual-branch If statement application, statement structure

For the two-branch selection structure, for the "condition", "condition is not established", both cases to perform different operations
1) For example: Write a connectivity test script pinghost.sh,
[Email protected] ~]# vim pinghost.sh
#!/bin/bash
Ping-c 3-i 0.2-w 3 $ &>/dev/null/Check to see if the target host is connected
If [$?-EQ 0]//Determine the return status of the previous command
Then
echo "host is up."
Else
echo "host is down."
Fi
[Email protected] ~]# chmod +x pinghost.sh
[Email protected] ~]#/pinghost.sh 192.168.1.1
Host 192.168.1.1 is up.
[Email protected] ~]#/pinghost.sh 192.168.1.0
Host 192.168.1.0 is down.
In the above script, "-C" is used to improve the test efficiency of the ping command. -I. -W, option, specify to send only three test packets, interval 0.2 seconds, time-out 3 seconds, in addition, through "&>/dev/null" to screen the ping command execution process output information.
2) again for example: through the shell script to check whether the VSFTPD service is running, if it has been run to list its listening address, PID number, otherwise the output hint "VSFTPD service is not available!" ”
First install the VSFTPD software, turn on the VSFTPD service (software CD)

Then write the script vim chkftpd.sh

[Email protected] ~]# chmod +x chkftpd.sh
[Email protected] ~]#./chkftpd.sh
JINGGAO:VSFTPD fuwubukeyong!
Set permissions and execute to prompt vsftpd service not available

Execute script again after opening VSFTPD server

3. Multi-Branch If statement application: Ability to perform different actions based on multiple mutually exclusive conditions, which is actually equivalent to nested use if statements.

For example: According to the different test scores entered to distinguish between excellent, qualified, unqualified three files
[Email protected] ~]# vim gradediv.sh

Execute script after setting permissions:
[Email protected] ~]# chmod +x gradediv.sh
[Email protected] ~]#./gradediv.sh
Qingshurunidefenshu (0-100): 90
Youxiu

Shell Scripting Basics App (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.