当前位置:网站首页>Shell script notes (5) - conditional statements of this
Shell script notes (5) - conditional statements of this
2022-04-23 00:04:00 【chauneyWang】
Conditional statement of script
Format of conditional test statement
| Format | |
|---|---|
| test < Conditions > | |
| [ < Conditions > ] | In general |
| [[ < Conditions > ]] | [] Upgraded version , Support Regular expressions |
| (( < Conditions > )) |
If you're not familiar with it, just man test see
File test statement
man test
There are probably the following operations for files
FILE1 -ef FILE2
FILE1 and FILE2 have the same device and inode numbers
FILE1 -nt FILE2
FILE1 is newer (modification date) than FILE2
FILE1 -ot FILE2
FILE1 is older than FILE2
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-g FILE
FILE exists and is set-group-ID
-G FILE
FILE exists and is owned by the effective group ID
-h FILE
FILE exists and is a symbolic link (same as -L)
-k FILE
FILE exists and has its sticky bit set
-L FILE
FILE exists and is a symbolic link (same as -h)
-O FILE
FILE exists and is owned by the effective user ID
-p FILE
FILE exists and is a named pipe
-r FILE
FILE exists and read permission is granted
-s FILE
FILE exists and has a size greater than zero
-S FILE
FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE
FILE exists and its set-user-ID bit is set
-w FILE
FILE exists and write permission is granted
-x FILE
FILE exists and execute (or search) permission is granted
# Test file permissions
wxl@ubuntu:~/workspace/shellScripts$ [[ -w test222.sh ]] && echo ok || echo error
error
wxl@ubuntu:~/workspace/shellScripts$ chmod 444 test222.sh
wxl@ubuntu:~/workspace/shellScripts$ [[ -w test222.sh ]] && echo ok || echo error
error
wxl@ubuntu:~/workspace/shellScripts$ ls -al test222.sh
-r--r--r-- 1 wxl wxl 0 Apr 4 05:30 test222.sh
wxl@ubuntu:~/workspace/shellScripts$ [[ -r test222.sh ]] && echo ok || echo error
ok
Common formats
# Execute a command when conditions are met
[ Conditions ] && command
# Execute multiple commands if conditions are met
[ Conditions ] && {
cmd1
cmd2
...
}
# If the conditions are not met, execute another command
[ Conditions ] || cmd
[ Conditions ] || {
cmd1
cmd2
...
}
Case study
Advanced version of computer
#! /bin/bash
[ $# -eq 2 ] || {
echo "Usage: Please input 2 numbers!!!"
exit 1
}
x=$1
y=$2
# Judge whether the current consecutive number is a number
expr "$x" + "$y" + 666 &>/dev/null
[ $? -eq 0 ] || {
echo "Usage: $0 num1 num2"
exit 2
}
echo "result: "
awk -va=$x -vb=$y 'BEGIN{print a+b,a-b,a*b,a/b}'
wxl@ubuntu:~/workspace/shellScripts$ sh cal.sh 10 10
result:
20 0 100 1
wxl@ubuntu:~/workspace/shellScripts$ sh cal.sh
Usage: Please input 2 numbers!!!
wxl@ubuntu:~/workspace/shellScripts$ sh cal.sh 10 a
Usage: cal.sh num1 num2
String manipulation You need to put double quotes
| expression | meaning |
|---|---|
| -n | Judgment string is not empty , return true |
| -z | Judge that the string is empty , return true |
| “str1” = “str2” | Two strings are equal , return true |
| “str1” != “str2” | Two strings are not equal , return true |
Code example :
# oldboy It's empty
wxl@ubuntu:~/workspace/shellScripts$ [ -n "$oldboy" ] && echo ok || echo fail
fail
# oldboy assignment
wxl@ubuntu:~/workspace/shellScripts$ oldboy=aaa
wxl@ubuntu:~/workspace/shellScripts$ [ -n "$oldboy" ] && echo ok || echo fail
ok
wxl@ubuntu:~/workspace/shellScripts$ [ -z "$oldboy" ] && echo ok || echo fail
fail
wxl@ubuntu:~/workspace/shellScripts$ [ -z "$oldboy11" ] && echo ok || echo fail
ok
# Determines whether the strings are equal
wxl@ubuntu:~/workspace/shellScripts$ name=zzz
wxl@ubuntu:~/workspace/shellScripts$
wxl@ubuntu:~/workspace/shellScripts$ [ "$name" = "zzz" ] && echo ok || echo fail
ok
wxl@ubuntu:~/workspace/shellScripts$ [ "$name" = "zz" ] && echo ok || echo fail
fail
wxl@ubuntu:~/workspace/shellScripts$ echo $nae
wxl@ubuntu:~/workspace/shellScripts$ echo $name
zzz
wxl@ubuntu:~/workspace/shellScripts$ [ "$name" != "zz" ] && echo ok || echo fail
ok
Be careful
- When executing the script, add -x Parameter indicates the execution process of the display script , When there are errors in the script, you can use to debug
- stay shell There are two ways to get the value of variables in programming or person perhaps or person {}
- ${#aa} Statistical variables aa The number of characters in $# Count the number of script parameters
- $$ The script pid
- | Said the pipe
- $! Of the last script pid
- #!/bin/bash Specify command interpreter
Comprehensive examples
- Remove comments and empty lines from the file
# Use three methods to solve
1. egrep
wxl@ubuntu:~/workspace/shellScripts$ egrep -v '#|^$' sshd_config
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# among ,^$ The corresponding regular expression ,^ Indicates the beginning of a line , such as ^name Already expressed name Line beginning with ;$ End of expression ,name$ Said to name The line at the end ;| Represents or
# Find the lines beginning with uppercase and lowercase letters in the file
wxl@ubuntu:~/workspace/shellScripts$ egrep '^[a-Z]' sshd_config
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
2. sed
wxl@ubuntu:~/workspace/shellScripts$ sed -r '/#|^$/d' sshd_config
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
# -r Indicates support for extended regular ,| Can express or
# //d Said to delete
3. awk
wxl@ubuntu:~/workspace/shellScripts$ awk '!/#|^$/' sshd_config
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
- obtain “aaa:444:444:/home/user” Medium home route
wxl@ubuntu:~/workspace/shellScripts$ variable="aaa:444:444:/home/user"
wxl@ubuntu:~/workspace/shellScripts$ echo ${variable##*:} Use ## Delete : Previous string
/home/user
wxl@ubuntu:~/workspace/shellScripts$ echo ${variable/*:/} Use // Replace : Previous string
/home/user
- Suffix the file html Batch change to bak
wxl@ubuntu:~/workspace/shellScripts$ for name in `ls *.html`;do echo $name ${name/.html/.bak} ;done
1.html 1.bak
2.html 2.bak
3.html 3.bak
index.html index.bak
- What are the common command interpreters ?
1. bash redhat、centos、ubuntu new edition
2. dash ubuntu Old version
2. csh tcsh unix System
- Command to get the name of the host hostname,ip,release edition , Kernel version
wxl@ubuntu:~/workspace/shellScripts$ hostname
ubuntu
wxl@ubuntu:~/workspace/shellScripts$ hostname -I|awk '{print $1}'
192.168.1.110
wxl@ubuntu:~/workspace/shellScripts$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.6 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.6 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
wxl@ubuntu:~/workspace/shellScripts$ uname -r
5.4.0-84-generic
- Command to get the current date , Time , working directory , user name
wxl@ubuntu:~/workspace/shellScripts$ date +%F
2022-04-12
wxl@ubuntu:~/workspace/shellScripts$ date +%T
07:37:48
wxl@ubuntu:~/workspace/shellScripts$ whoami
wxl
wxl@ubuntu:~/workspace/shellScripts$ pwd
/home/wxl/workspace/shellScripts
- Convert lowercase letters in the file to uppercase
wxl@ubuntu:~/workspace/shellScripts$ tr 'a-z' 'A-Z' <test18.cpp
ABCD
DFGH
IJKL
MNOP
QRST
wxl@ubuntu:~/workspace/shellScripts$ cat test18.cpp
abcd
dfgh
ijkl
mnop
qrst
wxl@ubuntu:~/workspace/shellScripts$ awk '{print toupper($0)}' test18.cpp
ABCD
DFGH
IJKL
MNOP
QRST
wxl@ubuntu:~/workspace/shellScripts$ awk '{print tolower($0)}' test18.cpp
abcd
dfgh
ijkl
mnop
qrst
- Check whether the user is root
wxl@ubuntu:~/workspace/shellScripts$ cat checkName.sh
#!/bin/bash
[ $UID -eq 0 ]||{
echo "need to be root"
exit 1
}
[ $UID -eq 0 ]&&{
echo "Now is root"
}
name=`whoami`
[ "$name" = "root" ]||{
echo "need to be root"
exit 1
}
[ "$name" = "root" ]&&{
echo "Now is root"
}
- To design a shell Program , Back up and compress on the first day of each month /workspace All the following , Store in /root/bak Directory , And the file name is in the following format yymmdd_bak, yy mm dd On behalf of
#!/bin/bash
dir=/home/wxl/workspace
time=`date +%y%m%d`
[ -d $dir ] || [ mkdir -p $dir ]
tar zcf ${dir}/${time}_bak.tar.gz /home/wxl/workspace/csdn_code
# back /home/wxl/workspace/csdn_code at first day of every month
# branch when Japan month Zhou 00 00 01 The first day of each month 0 spot 0 Start the save operation in minutes
00 00 01 * * /bin/sh /home/wxl/workspace/shellScripts/backFile.sh &>/home/wxl/workspace/log
- Count the users currently logged in to the computer
# It's actually statistics /etc/passwd Below /bin/bash Number of command interpreters
wxl@ubuntu:~$ grep -c "/bin/bash" /etc/passwd
2
- Remove all spaces in the string
wxl@ubuntu:~$ str='I am aaa'
wxl@ubuntu:~$ echo ${str// /}
Iamaaa
# Use tr
wxl@ubuntu:~$ echo ${str}|tr -d ' '
Iamaaa
# Use sed
echo $str|sed 's# ##g'
- Redirect standard output and standard error to log.txt
cmd &>/dev/log.txt
cmd >/dev/log.txt 2>&1
- v a l : − 10 and {val:-10} and val:−10 and {val: -10} The difference between
${val:-10} Said if val If it is undefined or empty , Set it to 10
${val: -10} Represents the last... Of the display variable 10 Characters
版权声明
本文为[chauneyWang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230003023407.html
边栏推荐
- B端/C端中,产品or运营哪个更重要?
- Failed to execute goal on project xxxxx
- 安川电机伺服软件SigmaWin+连接伺服驱动器无法连接问题
- 网站被DDOS攻击了怎么办?
- (mm-2018) local convolutional neural network for pedestrian re recognition
- 基于.NetCore开发博客项目 StarBlog - (3) 模型设计
- 字體自適應
- The implementation principle and function of closure and memory leakage
- 学习 Rust
- Reg 正则表达式学习笔记
猜你喜欢

Reg 正则表达式学习笔记

Write a beautiful login page with fluent (latest version)

B端/C端中,产品or运营哪个更重要?

The latest MySQL tutorial is easy to understand

Some understanding of image receptive field

FPGA (V) one of RTL codes (cross clock domain design)

OpenCV中保存不同深度图像的技巧

Compared with the traditional anchor based method, fcos is unique

FCOS中相较传统anchor-based方法中独特的地方

BGP基本配置
随机推荐
庞加莱球模型
Ansible job 1
[necessary knowledge] three dimensional imaging principle of line laser scanning
Wechat applet page Jump
网站被DDOS攻击了怎么办?
Codeforce 1669 A and B
Select all text
SystemVerilog verification - Test Platform writing guide learning notes (3): connecting design and test platform
获取某一点的颜色
彻底解决Failed to execute goal on project xxxxx
字體自適應
L1-080 乘法口诀数列 (20 分)
2022-04-22: give you a matrix board with the size of m x n to represent the deck, where each cell can be a warship 'x' or an empty space ', Returns the number of warships placed on the deck board. war
获取当前选中字符串的范围
Project training - Kid zombie
A convnet for the 2020s summary
【事务管理】
XPath positioning
Target detection model regression anchor offset and other problems
图像感受野的一些理解