当前位置:网站首页>Shell condition test, judgment statement and operator of shell system learning
Shell condition test, judgment statement and operator of shell system learning
2022-07-27 07:36:00 【edenliuJ】
Catalog
Multi conditional judgment statement case
Self increasing / The subtraction operator
The base of a numeric constant
Conditions for testing
Conditional test statements are used to test whether the specified conditional expression is true or false . When the condition is true, it returns 0, Conversely, return non 0 value . This is contrary to general programming languages , Please pay attention .
There are two kinds of syntax for conditional testing : Namely test command and [ command .
test expression
[ expression ]The parameter expression Is a conditional expression , Can be represented by a string 、 Numbers 、 file name , And various operators .
[ Command and test command , It also tests the following conditional expressions , But in order to increase the readability of the program ,Shell It is required to add a right square bracket to the right of the conditional expression ] Come with the front [ Command pairing ,
Be careful expression and [,] There is a space between ! because " Left bracket " It's the same thing shell command , There must be a space between the command and the parameter .
String test
The judgment of string is mainly to judge whether it is empty , Whether it is equal or not . Users can use the 5 Operators
| Operator | explain |
|---|---|
| string | Judge whether the specified string is empty , Not empty return 0 |
| string1 = string2 | Determine whether two strings are equal , Equal return 0 |
| string1 != string2 | Determine if two strings are not equal , Unequal return 0 |
| -n string | Judge string Whether it is a non empty string , Not empty return 0 |
| -z string | Judge string Whether it is an empty string , Empty string return 0 |
For the first operator in the above table , Only use test Order to test , rest 4 Kind of , Both test methods support .
In string comparison , It's a good habit to use quotation marks to define strings .
#!/bin/bash
a="abc"
b=""
test $a
# Not empty return 0
echo $?
test $b
# Null return non 0
echo $?
test -n $a
# Not empty return 0
echo $?
test -z $a
# Non empty returns non 0
echo $?
[ -n $a ]
# Not empty return 0
echo $?
[ -z $a ]
# Non empty returns non 0
echo $?
test "$a" = "$b"
# Inequality returns non 0
echo $?
[ "$a" != "$b" ]
# Unequal return 0
echo $?give the result as follows :
[email protected]:~/Documents/Shell$ ./4-1.sh
0
1
0
1
0
1
1
0
Be careful : String comparisons are case sensitive .
there = and != All operators , In use , You need to add spaces before and after , Bear in mind .
Integer test
The two syntaxes of integer testing are similar to strings :
test number1 op number2
[ number1 op number2]number1 and number2 Represents the integer involved in the comparison , It can be constants and variables ,op Representation operator . The following table lists the commonly used integer operators :
| Operator | explain |
|---|---|
| num1 -eq num2 | To determine if two Numbers are equal , Equal return 0 |
| num1 -ne num2 | Determine if two Numbers are not equal , Unequal return 0 |
| num1 -gt num2 | Judge num1 Is it greater than num2, Greater than return 0 |
| num1 -lt num2 | Judge num1 Is less than num2, Less than return 0 |
| num1 -ge num2 | Judge num1 Greater than or equal to num2, Greater than or equal to returns 0 |
| num1 -le num2 | Judge num1 Less than or equal to num2, Less than or equal to returns 0 |
example :
#!/bin/bash
a=12
b=14
[ "$a" -eq "$b"]
# Inequality returns non 0
echo $?
test "$a" -ne "$b"
# Unequal return 0
echo $?
[ "$a" -eq 12 ]
# Equal return 0
echo $?
[ "$a" -gt "$b" ]
# Not greater than return non 0
echo $?
[ "$a" -lt "$b" ]
# Less than return 0
echo $?
[ "$a" -ge "12" ]
# Greater than or equal to returns 0
echo $?result :
[email protected]:~/Documents/Shell$ ./4-2.sh
1
0
0
1
0
0
If [] There is no space between , Providing will report an error , For example, I ] No space before , The system prompts missing ] Symbol :
./4-2.sh: line 5: [: missing `]'
File test
Shell Many file related operators are provided to detect files . The following table :
| The operator | explain |
|---|---|
| -a file | Judge whether the file exists , There is returned 0 |
| -b file | Determine whether the file exists and the file type is block file , Is to return 0 |
| -c file | Determine whether the file exists and the file type is character file , Is to return 0 |
| -d file | Determine whether the file exists and the file type is directory , Is to return 0 |
| -e file | Effect and -a identical |
| -f file | Determine whether the file exists and is a regular file , Is to return 0 |
| -s file | Judge file Is it a non empty file , Is to return 0 |
| -w file | Determine whether the file exists and can be written , Is to return 0 |
| -r file | Determine whether the file exists and is readable , Is to return 0 |
| -x file | Determine whether the file exists and is executable , Is to return 0 |
| -L file | Determine whether the file exists and whether the file is a symbolic link , Is to return 0 |
| -u file | Determine whether the file exists and whether it is set suid position , Is to return 0 |
Main detection 3 aspect : Does the file exist ; Type of file ; Access to files .
First, create a directory and some files in a directory , The situation is as follows :
[email protected]:~/Documents/Shell/4-3$ ll
total 16
drwxrwxr-x 3 eden_ubuntu eden_ubuntu 4096 Jul 26 00:26 ./
drwxrwxr-x 3 eden_ubuntu eden_ubuntu 4096 Jul 26 00:18 ../
-rw-rw-r-- 1 eden_ubuntu eden_ubuntu 0 Jul 26 00:26 file1
-rw-rw-r-- 1 eden_ubuntu eden_ubuntu 3 Jul 26 00:27 file2
lrwxrwxrwx 1 eden_ubuntu eden_ubuntu 9 Jul 26 00:19 shortcut.sh -> ../4-2.sh*
drwxrwxr-x 2 eden_ubuntu eden_ubuntu 4096 Jul 26 00:18 tmpDir/
Execute the test case :
#!/bin/bash
test -d tmpDir
echo $?
test -f file1
#file1 Exists and is a normal file
echo $?
test -s file1
#file1 The size is 0, Return non 0
echo $?
test -s file2
#file1 Exist and file1 Size greater than 0, return 0
echo $?
test -L shortcut.sh
#shortcut.sh Exists and is a symbolic link , return 0
echo $?
test -b file1
#file1 Not a block file , Return non 0
echo $?
test -b /dev/sda
#/dev/sda Exist and /dev/sda It's a file , return 0
echo $?
test -c /dev/tty
# Control terminal /dev/tty Exist and /dev/tty Is a character file , return 0
echo $?result :
[email protected]:~/Documents/Shell/4-3$ ./4-3.sh
0
0
1
0
0
1
0
0
Logical operators
stay Shell Programming , We often encounter the situation of judging multiple conditions , Combine multiple conditions into one condition for judgment , be used Not 、 or and And The logic of . Look at the table below
| The operator | explain |
|---|---|
| ! expression | Logic is not |
| expression1 -a expression2 | Logic and |
| expression1 -o expression2 | Logic or |
A simple example :
#!/bin/bash
a=35
test "$a" -gt 30 -a "$a" -lt 40
echo $? give the result as follows :
[email protected]:~/Documents/Shell$ ./4-4.sh
0
Conditional judgment sentence
Conditional judgement sentences enable programs to execute different program branches according to different conditions , Mainly if sentence ,if else sentence ,if elif sentence , Examples of various statements are listed below .
if sentence
The grammar is :
if expression
then
statement1
statement2
...
fi
To make the code more compact , We can get if Clause and then Clause on one line , You need to be in expression Add a... After the expression ; Number
if expression; then
statement1 statement2 ...
fi
perhaps
if expression; then statement1 statement2 ...; fi
Examples are as follows :
#!/bin/bash
if [ -f ./4-5.sh ]
then
echo "./4-5.sh is a file"
fi
if test -f ./4-5.sh
then echo "./4-5.sh is a file"
fi
if [ -f ./4-5.sh ]; then echo "./4-5.sh is a file"; fi
if :; then echo "always ture"; fi
You can see if It can be used in the back test command , It can also be used. [ command
The result is :
[email protected]:~/Documents/Shell$ ./4-5.sh
./4-5.sh is a file
./4-5.sh is a file
./4-5.sh is a file
always ture
stay Shell There is also a special command in , be called An empty command , It is represented by a colon :, Change the order and do nothing , But its exit state is always 0, Is always true , In the above example, we have shown .
Others like to use && Operator instead of if sentence , Like the following example :
#!/bin/bash
test -f './4-5.sh' && echo './4-5.sh is a file'
! test -f './4-5-.sh' && echo './4-5.sh is not a file'; exit 1result :
[email protected]:~/Documents/Shell$ ./4-6.sh
./4-5.sh is a file
./4-5.sh is not a file
if else sentence
The grammar is :
if expression
then
statement1
statement2
...
else
statement3
statement4
...
fiif elif sentence
The grammar is :
if expression1
then
statement1
statement2
...
elif expression2
then
statement3
statement4
...
...
else
statementn
fi
I won't talk more about the above two sentences , Similar to other languages , know if Usage of , The two are similar .
Multi conditional judgment statement case
Be similar to C++,java Yes. switch sentence , The grammar is as follows :
case variable in
value1)
statement1
...
statementn
;;
value1)
statement1
...
statementn
;;
value1)
statement1
...
statementn
;;
*)
statement1
...
statementn
;;
esacamong *) Namely default Options , When there are no other branches, it will enter this branch .
case The sentence structure is in esac ending , and if Statement to fi Same structure , They all end with the command name in reverse order .
Operator
In addition to the operators listed above , There are also some operators related to numbers , Like arithmetic operators 、 An operator 、 Self increasing / Subtraction operator, etc . First, let's look at arithmetic operators , Similar to other programming languages
Arithmetic operator
| Operator | explain |
|---|---|
| + | Find the sum of two numbers |
| - | seek 2 The difference between numbers |
| * | seek 2 The product of numbers |
| / | seek 2 Quotient of numbers |
| % | Seeking remainder / modulus |
| ** | Power operation , This is special , give an example :3**4 Namely 3 Of 4 The next power |
Let's look at the compound arithmetic operator , This and C The language is the same , Don't explain too much
| Operator | explain |
|---|---|
| += | After summing up , Then assign and to the variable on the left |
| -= | After calculating the difference , Then assign and to the variable on the left |
| *= | After finding the product , Then assign and to the variable on the left |
| /= | After seeking business , Then assign and to the variable on the left |
| %/ | After taking the rest , Then assign and to the variable on the left |
An operator
Shell Programming also supports bitwise operators , Usage and C The language is the same , But it may be used less , Now let's look at the watch
| Operator | |
|---|---|
| << | Move left |
| >> | Move right |
| & | Bitwise AND |
| | | Press bit or |
| ~ | Bitwise non |
| ^ | Bitwise XOR |
Bitwise operators also have compound operators
| Operator | |
|---|---|
| >>= | After moving left, assign the value to the variable on the left |
| <<= | After moving to the right, assign the value to the variable on the left |
| &= | Assign the value to the variable on the left by bitwise and post |
| |= | Assign the value to the variable on the left by bit or after |
| ^= | Assign the value to the variable on the left after bitwise XOR |
Self increasing / The subtraction operator
Usage and C The language is the same
| Operator | explain |
|---|---|
| ++variable | First the variable The value of the add 1, And then assign it to variable |
| --variable | First the variable The value of the reduction 1, And then assign it to variable |
| variable++ | First use variable Value , And then variable The value of the add 1 |
| variable-- | First use variable Value , And then variable The value of the reduction 1 |
Perform arithmetic operations
stay Shell There is 4 There are three ways to perform arithmetic operations , They are as follows :
Use $((expression))
Using this form for arithmetic operations is relatively free , There is no need to escape operators and parentheses , Expressions can be written in a loose or compact format . give an example :
#!/bin/bash
# In compact format
result=$((3+7))
echo "$result"
# In a loose format
result=$(( 3 - 7 ))
echo "$result"
result=$((3*7))
echo "$result"
result=$((8/3))
echo "$result"
result=$((8%3))
echo "$result"
result=$((2**3))
echo "$result"
# Compound operation
result=$(((3+7)*2))
echo "$result"result :
[email protected]:~/Documents/Shell$ ./4-7.sh
10
-4
21
2
28
20
Use $[expression]
This method of use is similar to $((expression)) Basically the same , give an example :
#!/bin/bash
# In compact format
result=$[3+7]
echo "$result"
# In a loose format
result=$[ 3 - 7 ]
echo "$result"
result=$[3*7]
echo "$result"
result=$[8/3]
echo "$result"
result=$[8%3]
echo "$result"
result=$[2**3]
echo "$result"
# Compound operation
result=$[(3+7)*2]
echo "$result"The result is consistent with the above .
[email protected]:~/Documents/Shell$ ./4-8.sh
10
-4
21
2
2
20
[] And (()) The difference is [] Assignment operation is not allowed inside , and (()) It supports assignment , This difference can be found later We can see in the example of the base of numerical constants , If you are interested, you can also try .
Use expr command
expr It's a Shell command , Use the syntax :
expr expression
It has more attention to use , It's not easy to use . When using operators , Operators need to be escaped , If there are parentheses , You also need to escape the parentheses . Cannot use compact format , Use loose formatting , give an example :
#!/bin/bash
result=`expr 2 + 100`
echo "$result"
result=`expr 2 - 100`
echo "$result"
result=`expr 2 \* 100`
echo "$result"
result=`expr 100 / 2`
echo "$result"
result=`expr 100 % 3`
echo "$result"
result=`expr \( 1 + 3 \) \* 5`
echo "$result"
# Wrong grammar
result=`expr 2+5`
echo "$result"
# Wrong grammar
result=`expr 2+5*10`
echo "$result"
# Wrong grammar
result=`expr 2*(2+5)`
echo "$result"result :
[email protected]:~/Documents/Shell$ ./4-9.sh
102
-98
200
50
1
20
2+5
2+5*10
./4-9.sh: command substitution: line 29: syntax error near unexpected token `('
./4-9.sh: command substitution: line 29: `expr 2*(2+5)'
You can see the front 6 Items are normal , To the first 7 Xiang and di 8 The result did not meet expectations , Not an integer value, but an expression , The first 9 Item reporting error . So pay attention to avoid the above mistakes when using .
Use let command
Use let The command can execute one or more arithmetic expressions , There is no need to use... For variable names $ Symbol . If the expression contains spaces or other special characters , Need to quote . give an example :
#!/bin/bash
n=10
let n=n+1
echo "$n"
let n-=1
echo "$n"
let n=n**2
echo "$n"
let n--
echo "$n"
let n**3
echo "$n"
let The expression of must have an assignment at the end to be effective . let n**3 It will not be modified n The value of the .
give the result as follows :
[email protected]:~/Documents/Shell$ ./4-10.sh
11
10
100
99
99
The base of a numeric constant
By default ,Shell Numbers are always represented in decimal . But users can also Shell Use other base numbers in to represent numbers , Like binary , octal , Hexadecimal . stay Shell in , Users can use two syntaxes to represent different base numbers
1. Add prefix :0 The first number indicates 0 Base number ,0x The first number indicates hexadecimal
2. Use # Number :2#1001 For binary ,8#20 For octal
Examples are as follows :
#!/bin/bash
a=$((2#1000))
((b=8#20))
((c=16#10))
d=$[0x10]
e=$[020]
f=20
((g=0x10))
((h=(1+3)*5))
echo "$a $b $c $d $e $f $g $h"
give the result as follows :
[email protected]:~/Documents/Shell$ ./4-11.sh
8 16 16 16 16 20 16 20
Summary
This article mainly discusses conditional testing , Judgment statement , Operator and how to use it
边栏推荐
- View the dmesg log before server restart
- 简单的轮播图
- SQL statement batch update time minus 1 day
- C语言实现猜数字小游戏项目实战(基于srand函数、rand函数,Switch语句、while循环、if条件判据等)
- 临界区(critical section 每个线程中访问 临界资源 的那段代码)和互斥锁(mutex)的区别(进程间互斥量、共享内存、虚拟地址)
- A small cotton padded jacket with air leakage
- 【WSL2】配置连接 USB 设备并使用主机的 USB 摄像头
- 使用sqlplus显示中文为乱码的解决办法
- Will Flink CDC constantly occupy Oracle's memory by extracting Oracle's data, and finally cause oracle-040
- js正则表达式实现每三位数字加一个逗号
猜你喜欢

我是不是被代码给耽误了……不幸沦为一名程序员……
![Multithreading [preliminary - Part 1]](/img/e6/5808bbdb8368bc780bde4c151e7cd7.png)
Multithreading [preliminary - Part 1]

用户解锁SM04 SM12

Perl: split the external command to be executed into multiple lines

Port forwarding summary

IO中节点流和处理流的理解学习

Single arm routing (explanation + experiment)

Array method and loop in JS

Top ten interview questions for software testing (with answers and analysis)

The DrawImage method calls the solution of not displaying pictures for the first time
随机推荐
(2022牛客多校三)A-Ancestor(LCA)
Top ten interview questions for software testing (with answers and analysis)
临界区(critical section 每个线程中访问 临界资源 的那段代码)和互斥锁(mutex)的区别(进程间互斥量、共享内存、虚拟地址)
Summary of several common ways to join dimension tables in Flink
查看服务器重启前的 dmesg 日志
Use Amazon dynamodb and Amazon S3 combined with gzip compression to maximize the storage of player data
flink中维表Join几种常见方式总结
Bingbing's learning notes: classes and objects (middle)
View the dmesg log before server restart
Oracle 组合查询
Using loops to process data in tables in kettle
Tableau prep is connected to maxcompute and only writes simple SQL. Why is this error reported?
冰冰学习笔记:类与对象(中)
Chapter 6 Shell Logic and Arithmetic
Prior Attention Enhanced Convolutional Neural Network Based Automatic Segmentation of Organs at Risk
Routing between VLANs (explanation + verification)
Okaleido ecological core equity Oka, all in fusion mining mode
Functools module
ARP broadcasting practice cases
Use reflection to dynamically modify annotation attributes of @excel