Shell script programming Selection Control Structure
There are two programming languages: interpreted language and compiled language. An interpreted language is an interpreted statement that can be executed on Demand Based on the process control mechanism. When a statement is interpreted, the result of the statement is returned. This language requires an interpreter, bash in linux is such an interpreter. Common interpreted languages include perl, python, ruby, and bash. To compile a language, you must first compile the source program and convert the source program to a binary format for execution. This language requires an editor, for example, gcc in linux is an editor, compiled languages include C, C ++, and C. Both interpreted and compiled languages have language control structures. programs without control structures cannot be regarded as good programs.
The language control structure is divided into three types:
Sequential execution: the default rule. Each statement is executed one by one.
Select execution: Conditional judgment. only partial execution meets the conditions.
Loop execution: execute the same code multiple times.
This blog shows how to select a control structure.
There are two types of Selection control structures in linux: if-then and case-esac.
1. if-then
Bash condition test:
[Expression]
[[Expression]
Test expression
Bash command
If-then has three structures:
Single branch if statement
If [condition]; then
Statement...
Fi
This single-branch statement runs the statement after then when the condition is met. If the condition is not met, it exits the judgment statement directly.
Eg: If a mysql user exists in the system, mysql exist is displayed.
#!/bin/bash#this shell test mysql user exist system.if id mysql ;then echo "mysql exist."fi
Dual-branch if statement
If [condition]; then
Statement...
Else
Statement...
Fi
When the conditions are met, the statement after then is run. If the conditions are not met, the statement after else is run.
Eg1: if the specified user is saved, it indicates that the user already exists and its ID and SHELL are displayed. Otherwise, the user is added and its ID is displayed.;
#!/bin/bashUsername=mysqlif id $Username &>/dev/null;then Id=`grep "^$Username\>" /etc/passwd | cut -d: -f3` Shell=`grep "^$Username\>" /etc/passwd | cut -d: -f7` echo "$Username exist,ID is $Id,shell is $Shell."else useradd $Username Id=`grep "^$Username\>" /etc/passwd | cut -d: -f3` echo "$Username ID is $Id."fi
Eg2: determines whether a user exists. If the user exists, the ID and SHELL are displayed. If the user does not exist, the user is added and its ID is displayed.
Analysis: This question is different from the previous column because it is not specified by the user. Since it is not specified, You need to manually shell a parameter, and how does the script reference the parameter. The location variable in the bash variable is used here.
Location variable: $1, $2... $9 ($1 is the first parameter passed by the script ...)
$0: Script Name
$ @: List of parameters for all locations
$ *: All location parameters
$ #: Number of location parameters
#!/bin/bashif id $1 &>/dev/null;then Id=`grep "^$1\>" /etc/passwd | cut -d: -f3` Shell=`grep "^$1\>" /etc/passwd | cut -d: -f7` echo "$1 exist,ID is $Id,shell is $Shell."else useradd $1 Id=`grep "^$1\>" /etc/passwd | cut -d: -f3` echo "$1 ID is $Id."fi
Run the script bash eg2.sh mysql eg. sh is the script name, and mysql is the first parameter passed to the script)
Eg3:A series of user names are passed to the script through parameters to allow the script to add these users; however, you must first determine whether the user exists, and then add the user;After the user is added, a total of several users are added. Of course, the user is not added because the user exists in advance;
Analysis: What this script does not know is that it does not know how many parameters need to be passed. Therefore, the location variable does not meet the requirements, so it references$ @This special variable, and then these users, You have to retrieve these users one by one, and then judge whether they exist, and use a loop to control how to retrieve these users one by one, then, the user cannot duplicate one by one, so the user must take a T$ @The user in the list, with the shift command, is the shift command in turn T except the user.
#!/bin/bashcount=0for user in $@;do if id $1 &>/dev/null;then echo "user $1 exsit." shift else useradd $1 count=$[$count+1] echo "add $1." shift fidoneecho "total users:$count"
Run scripts
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131227/1I239D41-0.png "title =" image 17.png"/>
Nested if statement (the most common nesting)
If [condition 1]; then
If [condition 2]; then
Statement...
Else
Statement .....
Fi
Else
Statement ....
Fi
This nested if statement is more complex. When condition 1 is met, the statement after the first then is run. After condition 1 is met, condition 2 is determined, when both conditions 1 and 2 are met, the statement after the second then is run. If condition 2 is not met, the statement after the first else is run, if neither condition 1 is met, run the statement following the second else.
Eg4: determines whether a user is a common user, a system user, or an admin user. If the user does not exist, the user does not exist.
Analysis: first, determine whether a user exists. If yes, compare whether the user ID is greater than or equal to 500. If the value is greater than or equal to 500, it indicates a common user, whether it is 1-499, yes indicates the System user. If it is 0, it indicates the admin user.
In this example, we also use a numerical comparison and a combination of conditions.
Linux test command supports numerical comparison, string comparison, and file comparison. For more information, see man test.
Numerical Comparison
Num1-eq num2 check whether num1 is equal to num2
Num1-ge num2 check whether num1 is> or equal to num2
Num1-gt num2 check if num1 is greater than num2
Num1-le num2 check if num1 is <equal to num2
Num1-lt num2 check whether num1 is <num2
Num1-ne num2 check if num1 is not equal to num2
Combination condition test
-A: With [$ Uid-ge 1-a $ Uid-le 499]
-O: or [$ Uid-eq 0-a $ Uid-ge 500]
! : Non, single object operator [! $ Uid-eq 0]
#!/bin/bashif id $1 &> /dev/null;then Id=`grep "^$1\>" /etc/passwd | cut -d: -f3` if [ $Id -ge 500 ];then echo "$1 is common user." elif [ $Id -lt 500 -a $Id -ge 1 ];then echo "$1 is system user." else echo "$1 is admin user." fielse echo "$1 Not exist."fi
Script Execution result
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131227/1I2391X6-1.png "title =" image 18.png"/>
Eg5: Determine whether the user's shell is a logon shell;
Analysis: first, determine whether the user's shell exists. If there is a user's shell in redhat, It is empty. If the shell exists, determine whether the shell is bash. If yes, it indicates a login user, if not, the user cannot log on. In version 5. x of redhat.
String comparison
Str1 = str2 check if str1 and str2 are the same
Str1! = Str2 check if str1 and str2 are different
Str1 <str2 check if str1 is smaller than str2
Str1> str2 check if str1 is greater than str2
-N str1 check if the str1 length is greater than 0
-Z str1: Check whether the str1 length is 0
= ~ : Determines whether the string on the Left can be matched by the pattern on the right. It is usually used in [[]; ["$ opt1" = ~ Pattern],
Generally, the beginning and end of a line are anchored.
#!/bin/bashShell=`grep "^$1:" /etc/passwd | cut -d: -f7`if [ -z $Shell ];then echo "$1 user no shell"else if [ "$Shell" == "/bin/bash" ]; then echo "$1 user shell is login shell." else echo "$1 user shell is nologin shell." fifi
Running result
650) this. width = 650; "src =" http://www.bkjia.com/uploads/allimg/131227/1I23a408-2.png "title =" image 19.png"/>
Eg6: determines the CPU manufacturer of the current host. Its information is in the/proc/cpuinfo file's vendor id line. If its producer is GenuineIntel, it will be displayed as Intel; otherwise, it will be displayed as AMD;
#!/bin/bashVendor=`grep "vendor_id" /proc/cpuinfo | uniq | cut -d: -f2`if [[ "$Vendor" =~ [[:space:]]*GenuineIntel$ ]]; then echo "Intel"else echo "AMD"fi
Running result
[Root @ Redhat5 test] # bash eg6.sh
Intel
Eg7:
Write a script: You can accept a parameter in the following format:
Script. sh {start | stop | restart | status}
If the parameter is start, create an empty file/var/lock/subsys/script and display "Starting script successfully .";
If the parameter is stop, delete the file/var/lock/subsys/script and display "Stop script finished .";
If the parameter is restart, delete the file/var/lock/subsys/script and create it again, and display "Restarting script successfully .";
If the parameter is status, then:
If the/var/lock/subsys/script file exists, it is displayed as "script is running ."
Otherwise, "script is stopped." is displayed ."
Other parameters: "script. sh {start | stop | restart | status}" is displayed }"
File comparison
-B file: Check whether the file exists and is a special block file.
-C file: Check whether the file exists and is a character file.
-D file: Check whether the file exists and is a directory.
-E file: Check whether the file exists.
-F file: Check whether the file exists and is a file.
-H file: Check whether the file exists and is a conforming link.
-R file: Check whether the file exists and is readable.
-S file check whether the file exists and is not empty
-W file: Check whether the file exists and can be written
-X file: Check whether the file exists and is executable.
-O file: Check whether the file exists and is not owned by the current user.
-G file: Check whether the group exists and whether the default group is the current user group.
#!/bin/bash#Author:litaotaodir=`basename $0`if [ $1 == "start" ];then touch /var/lock/subsys/$dir echo "Starting script successfully."elif [ $1 == "stop" ];then rm /var/lock/subsys/$dir &> /dev/null echo "Stop script finished."elif [ $1 == "restart" ];then rm /var/lock/subsys/$dir &> /dev/null touch /var/lock/subsys/$dir echo "Restarting script sucessfully."elif [ $1 == "status" ];then if [ -e /var/lock/subsys/$dir ];then echo "script is running." else echo "script is stopped." fielse echo "$dir.sh {statr|stop|restart|status}"fi
Run bash eg6.sh start. You can copy the shell and run the analysis results again.
This article is from the "technical path-NLP" blog, please be sure to keep this source http://litaotao.blog.51cto.com/6224470/1253744