In bash, if can choose and execute statements, and if condition tests include three forms: integer test, character test, and file test.
if format
Single branch syntax
if condition; then Statement1 Statement2 ... fi
Double branch syntax
if condition;then Statement1 Statement2 else Statement2 fi
Multi-branch syntax
if condition1; then Statement1 Statement2 elif condition2; then Statement1 Statement2 else Statement1 Statement2 fi
Conditional testing
If the judgment conditions can be found in the following forms
- [ express ]
- [[ express ]]
- test express
- bash command (execute the statement if the command is executed successfully)
[],[[]], test functions similarly, basically it can be interchanged when writing bash scripts
Note: [],[[]] space position;
[1 space + expression + 1 space]
[[1 space + expression + 1 space]]
Example: bash command to do if condition
Example 1: Check whether there is a hadoop user in the system. If there is a uid and shell, no return
[root@node1 bash_test]# cat #!/bin/bash if id -u hadoop &> /dev/null;then grep "^hadoop" /etc/passwd | cut -d: -f1,7 else echo no fi [root@node1 bash_test]# ./ hadoop:/bin/bash
Notice:
- id -u hadoop &> The function of the /dev/null directive is to execute id -u hadoop to throw away its receipt (not displayed in the terminal)
- When the bash command performs if condition, when the command status return value is true, that is, the value is 0, the condition is satisfied: the command status return value 1-255 means that the condition is not satisfied
Command status return value
We can use $? to view the command status return value of the previous command. The command will return 0 after successful execution, and the command will return 1 after failure execution.
[root@node1 bash_test]# id hadoop uid=4024(hadoop) gid=4024(hadoop) Group=4024(hadoop),4026(mygrp) [root@node1 bash_test]# echo $? 0 [root@node1 bash_test]# id hadoop111 id: hadoop111: no such user [root@node1 bash_test]# echo $?
Of course, in bash scripts, we can use exit to exit the program, and the number followed by represents the command execution status. For example: exit 0 means execution success, exit 1 means execution failure
Integer test
If conditional test is to compare integers, the specific rules are as follows
expression: value 1 comparison symbol value 2
Comparison symbols:
Greater than -gt
greater than or equal to -ge
equal to -eq
Not equal to -ne
Less than -gt
Less than or equal to -ge
Example 1: Read a parameter, if it is less than 10, returns Yes, and returns No if it is greater than 10.
[root@node1 bash_test]# cat #!/bin/bash if [ $1 -lt 10 ];then echo Yes else echo No fi [root@node1 bash_test]# ./ 5 Yes [root@node1 bash_test]# ./ 11 No
Note: $1 represents the first parameter passed in by the terminal
The position variables in bash are:
$1,$2,$3…
$@ $* Show all position variables
$@ Five strings are displayed as one string
$* Five strings are displayed separately
$# Displays the number of position variables
$? Save the status return value of the command just executed
shift implements positional parameter rotation
Combining shfit can use a $1 to get all variables
shift 2 Specify rotation 2
For example: execute command./ 5
$0 is ./
$1 is 5
@ and @ and @ and * are both "./ 5"
$# is 1
Example 2: Write a script to generate two numbers randomly and compare their sizes
[root@node1 bash_test]# cat #!/bin/bash A=$RANDOM B=$RANDOM result="" if [ $A -lt $B ];then result="A is greater than B" elif [ $A -gt $B ];then result="A is less then B" else result="A equals B" fi echo "A = $A, B = $B, $result" [root@node1 bash_test]# ./ A = 6646, B = 3889, A is less then B
$RANDOM generates a random number between 0-32767
Character Test
If the condition is the size comparison of characters, the size comparison is done by default with the ASCII code table.
In addition to using the symbols -lt, -gt, -le, -ge, -eq, -ne for judgment, we can also use the following symbols for judgment.
> : Greater than
< : Small
== : equal to
!= : Not equal to
Monogram test
-z $STRING The length of the string, if it is empty, it is true, if it is not empty, it is false
-n $STRING is empty, it is false, and if it is not empty, it is true
=~ Determine whether the string on the left can be matched by the pattern on the right, usually used in double[[ ]]
Generally, the beginning of the line is used, and the end of the line is anchored $, and the beginning of the word cannot be anchored\< \>
Cannot use quotes
Generally, we use == more often to determine whether two strings are equal.
Example 1: When writing a script, you can accept a parameter, and its usage form is as follows:
{start|stop|restart|status}
in:
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 successfully."
If the parameter is restart, delete the file /var/locksubsys/script and recreate it, and then "Restarting script successfully."
If the parameter is status, then: if the file /var/lock/subsys/script exists, "Script is running..." is displayed, otherwise, "Script is stopped."
Any other parameters; display "{start|stop|restart|status}"
#!/bin/bash # echo $1 if [ $1 == "start" ];then if [ -e /var/lock/subsys/script ];then echo "script is already running." else mkdir /var/lock/subsys/script echo "Starting script successfully." fi elif [ $1 == "stop" ];then if [ -e /var/lock/subsys/script ];then rm -rf /var/lock/subsys/script echo "Stop script finished." else echo "script is stopped yet." fi elif [ $1 == "restart" ];then rm -rf /var/lock/subsys/script mkdir /var/lock/subsys/script echo "Restarting script successfully." elif [ $1 == "status" ];then if [ -e /var/lock/subsys/script ];then echo "script is running." else echo "script is stopped." fi else echo " {start|stop|restart|status}" fi
File Testing
There are mainly the following types of operations on files
Monogram test
-f Test whether it is a normal file, that is, a file whose file type is - when ls -l
-d Test whether it is a directory file, that is, the directory with the file type of - when ls -l
-e Test whether the file exists, and existence is true
-r,-w,-x are all the three judging file permissions and whether they have read, write, and execute permissions
-s Test whether the file size is not empty. If it is not empty, it is true. If it is empty, it is false.
-l -b -c determines whether the file is of the corresponding type
Example: If /tmp/test10 does not exist, create it
[root@node1 bash_test]# cat #!/bin/bash if [ ! -e /tmp/test10 ];then mkdir /tmp/test10 fi [root@node1 bash_test]# ls -ld /tmp/test10 ls: Unable to access/tmp/test10: There is no file or directory [root@node1 bash_test]# ./ [root@node1 bash_test]# ls -ld /tmp/test10 drwxr-xr-x 2 root root 6 8moon 1 21:21 /tmp/test10
Combination condition test
When there are multiple judgments to be made, you can use the following to connect
symbol | Symbol meaning | Example | explain |
---|---|---|---|
-a | And, both left and right sides of the symbol need to be satisfied; | [ $A > 300 -a $A < 500 ] | The value of the A variable is greater than 300 and must be less than 500 to meet the conditions |
-o | Or, only one is satisfied on the left and right sides of the symbol; | [ $B < 10 -o $A > 100 ] | Variable B is less than 10 or Variable A is less than 100 |
! | No, reverse the result; | [ ! id hadoop &> /dev/null ] | If there is no hadoop user, the condition is met |
If using independent commands to combine conditions, use &&,|| or,!
Example 1: Write a script, given the user, if there is no exit script
[root@node1 bash_test]# cat #!/bin/bash if ! id $1 > /dev/null;then echo "no find this user" exit 6 else id $1 fi [root@node1 bash_test]# ./ hadoop uid=4024(hadoop) gid=4024(hadoop) Group=4024(hadoop),4026(mygrp) [root@node1 bash_test]# ./ hadoop1 id: hadoop1: no such user no find this user
Example 2: Pass a string to the script through parameters. If the passed string is "memory" or "Memory", the memory information of the current host is displayed in MB: Otherwise, the contents of the /proc/uptime file are displayed.
#!/bin/bash if [[ $1 == "memory" || $1 == "Memory" ]]; then free -tm else cat /proc/uptime fi
Notice:
|| Short circuit operation, the front is true, and the back will not be run
&& The front is false, no calculation is required
If we need to have the previous one as false, run the subsequent program, use ||
If we need the front to be true, run the later program, use &&
Example 1: Create /tmp/test10 if it does not exist
[ -e /tmp/test10 ] || mkdir /tmp/test10
Example 2: If the /tmp/test10 folder exists, create a hello file under that folder
[ -d /tmp/test10 ] && touch /tmp/test10/hello
Example 3: If the /tmp/test10/hello file exists, it will show 'exist'; if it does not exist, it will show 'not exist'
[ -f /tmp/test10/hello ] && echo "exist" || echo "not exist"
This is the end of this article about the use of bash if condition judgment. For more related bash if condition judgment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!