当前位置:网站首页>If condition judgment in shell language
If condition judgment in shell language
2022-04-23 18:14:00 【The hunter is eating meat】
List of articles
1、if Basic syntax :
if [ command ];then
A statement executed under this condition
elif [ command ];then
A statement executed under this condition
else
A statement executed under this condition
fi
2、 String judgment
When the string batch is small , Variables must use Double quotes .
[ -z "str" ] If str The length of is zero , It is true , That is to judge whether it is empty , Empty is true ;
[ -n "str" ] If str The length of is non-zero , It is true , That is, judge whether it is non empty , Not empty is true ;
[ "str1" = "str2" ] If two strings are the same , It is true ;
[ "str1" != "str2" ] If the strings are different , It is true ;
[ "str1" ] If the string is not empty , It is true , And -n similar .
Example :
if [ -z "$path" ]; then
echo "head Please specify path Value " 1>&2
fi
if [ "$opt" != "-" ]&&[ "$opt" != "+" ]; then
echo "opt Only value - or +" 1>&2
exit 1;
fi
3、 Numerical judgment
Never use the greater than sign for numerical comparison 、 Less than no. , Numerical comparisons can only be made using -eq 、-gt etc. .
[ num1 -eq num2 ] num1 and num2 It is true that two numbers are equal , =
[ num1 -ne num2 ] num1 and num2 Two numbers are not equal to true ,!=
[ num1 -gt num2 ] num1 Greater than num1 It's true , >
[ num1 -ge num2 ] num1 Greater than or equal to num2 It's true , >=
[ num1 -lt num2 ] num1 Less than n um2 It's true , <
[ num1 -le num2 ] num1 Less than or equal to num2 It's true , <=
Example :
if [ ${num1} -gt ${num2} ]; then
echo "[ Relative catalog ] The length of should be less than [ File path ] The length of "
exit 1
fi
4、 Judgment of files and directories
[ -e file ] If file There is , It is true .
[ -d DIR ] If file There is , And it's a directory , It is true .
[ -f file ] If file There is , And it's an ordinary file , It is true .
[ -r file ] If file Exist and readable , It is true .
[ -w file ] If file Exists and is writable , It is true .
[ -x file ] If file Existing and executable , It is true .
[ -b file ] If file There is , And is a block special file , It is true .
[ -c file ] If file There is , And it's a word special file , It is true .
[ -g file ] If file Exists and has been set SGID, It is true .
[ -k file ] If file The adhesive bit exists and has been set , It is true .
[ -p file ] If file There is and is a name pipeline (F If O), It is true .
[ -s file ] If file Exist and not of size 0, It is true .
[ -t FD ] If the file descriptor FD Open and point to a terminal , It is true .
[ -u file ] If file Exist and set SUID (set user ID), It is true .
[ -O file ] If file Exists and is a valid user ID, It is true .
[ -G file ] If file Exists and belongs to a valid user group , It is true .
[ -L file ] If file Exists and is a symbolic connection , It is true .
[ -N file ] If file There is and has been mod, If ied since it was last read It is true .
[ -S file ] If file Exists and is a socket , It is true .
[ file1 -ot file2 ] If file1 Than file2 To the old , perhaps file2 Exist and file1 Do not save , It is true in .
[ file1 -ef file2 ] If file1 and file2 Point to the same device and node number , It is true .
5、 Complex logical judgment
| operation | explain |
|---|---|
| -a | And |
| -o | or |
| ! | Not |
Example 1: And Use
If a>b And a< c
if (( a > b )) && (( a < c ))
perhaps
if [[ $a > $b ]] && [[ $a < $c ]]
perhaps
if [ $a -gt $b -a $a -lt $c ]
in addition ,“||“ and ”&&” stay shell It can be used in , As shown below :
if [ a>b && a < c ]
Example 2: or Use
If a>b or a < c
if (( a > b )) || (( a < c ))
perhaps
if [[ $a > $b ]] || [[ $a < $c ]]
perhaps
if [ $a -gt $b -o $a -lt $c ]
in addition ,“||“ and ”&&” stay shell It can be used in , As shown below :
if [ a>b || a < c ]
5、 give an example
#!/bin/bash
#echo -n "please input your score:"
#read score
#echo "input score is $ score "
read -p "please input a score:" score
echo -e "your score [$score] is judging by sys now"
if [ "$score" -ge "0" ]&&[ "$score" -lt "60" ];then
echo "sorry,you are lost!"
elif [ "$score" -ge "60" ]&&[ "$score" -lt "85" ];then
echo "just soso!"
elif [ "$score" -le "100" ]&&[ "$score" -ge "85" ];then
echo "good job!"
else
echo "input score is wrong , the range is [0-100]!"
fi
6、 Conditional variable substitution :
Bash Shell You can perform conditional substitution of variables , That is, only when certain conditions occur , The replacement condition is placed in {} in .
(1) ${value:-word}
When the variable is undefined or the value is empty , The return value is word The content of , Otherwise, return the value of the variable .
(2) ${value:=word}
Similar to the former , Only if the variable is undefined or the value is empty , Back in word Value , At the same time word Assign a value to value
(3) ${value:?message}
If a variable is assigned a value , Normal replacement . otherwise , The message is message Send to standard error output .( If this substitution appears in Shell In the program , Then the program will terminate )
(4) ${value:+word}
If a variable is assigned a value , Only its value can be used word Replace , otherwise , No replacement .
(5) ${value:offset}, ${value:offset:length}
Extract substrings from variables , here offset and length It can be an arithmetic expression .length When not specified , The default is from offset Length from start to end .
path="C:\Users\admin\AppData\Roaming"
echo ${path:4}
The result is sers/admin/AppData/Roaming
path="C:\Users\admin\AppData\Roaming"
echo ${path:0:2}
The result is C:
path="C:\Users\admin\AppData\Roaming"
echo ${path:0-7}
Roaming
(6) ${#value}
The number of characters in the variable , length .
(7) ${value#pattern}, ${value##pattern}
Get rid of value China and pattern Matching parts , On the condition that value Start with pattern Match , # And ## The difference is that one is the shortest matching pattern , One is the longest matching pattern .
(8) ${value%pattern} , ${value%%pattern}
On (7) similar , Just from value The tail of pattern Match , % And %% The difference between # And ## equally
(9) ${value/pattern/string}, ${value//pattern/string}
Replace the contents of the variable , with pattern Replace the matching part with string The content of , / And // The difference is the same as above .
path="C:\Users\admin\AppData\Roaming"
path=${path//'\'//}
echo $path
The input result is
C:/Users/admin/AppData/Roaming
版权声明
本文为[The hunter is eating meat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210611118105.html
边栏推荐
- Analysez l'objet promise avec le noyau dur (Connaissez - vous les sept API communes obligatoires et les sept questions clés?)
- 【ACM】509. Fibonacci number (DP Trilogy)
- ArcGIS table to excel exceeds the upper limit, conversion failed
- Visualization of residential house prices
- Mode of interprocess communication
- Queue solving Joseph problem
- Rust: the output information of println is displayed during the unit test
- C language to achieve 2048 small game direction merging logic
- Software test summary
- Cygwin64 right click to add menu, and open cygwin64 here
猜你喜欢

Random number generation of C #

JD-FreeFuck 京東薅羊毛控制面板 後臺命令執行漏洞

Deep learning classic network analysis and target detection (I): r-cnn

From source code to executable file

Gobang game based on pyGame Library

QT reading and writing XML files (including source code + comments)

Robocode tutorial 7 - Radar locking

.104History

Calculation of fishing net road density

STM32 learning record 0008 - GPIO things 1
随机推荐
From introduction to mastery of MATLAB (2)
Map basemap Library
Hard core parsing promise object (do you know these seven common APIs and seven key questions?)
解决报错max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
Secure credit
JD freefuck Jingdong HaoMao control panel background Command Execution Vulnerability
Nanotechnology + AI enabled proteomics | Luomi life technology completed nearly ten million US dollars of financing
[UDS unified diagnostic service] v. diagnostic application example: Flash bootloader
WIN1 remote "this may be due to credssp encryption Oracle correction" solution
mysql自动启动设置用Systemctl start mysqld启动
Vulnérabilité d'exécution de la commande de fond du panneau de commande JD - freefuck
Crawl the product data of Xiaomi Youpin app
Serialization scheme of serde - trust
【ACM】376. Swing sequence
Realization of consumer gray scale
C byte array (byte []) and string are converted to each other
Identification verification code
Array rotation
Docker 安裝 Redis
Implement a simple function to calculate the sum of all integers between M ~ n (m < n)