当前位置:网站首页>Shell (II)
Shell (II)
2022-07-28 11:41:00 【JiaXingNashishua】
Catalog
3、 ... and : Getting started with regular expressions
3.2 Special characters are often used
5、 ... and : Comprehensive application case
One :read Read console input
1) Basic grammar
read ( Options ) ( Parameters )
① Options :
-p: Specify the prompt when reading the value ;
-t: Specifies the time to wait while reading the value ( second ) If -t Not adding means waiting ② Parameters
Variable : Specifies the variable name of the read value
2) Case practice
Tips 7 Seconds , Read the name entered by the console
[[email protected] shells]$ touch read.sh
[[email protected] shells]$ vim read.sh
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds :" NN
echo $NN
[[email protected] shells]$ ./read.sh
Enter your name in 7 seconds : atguigu
atguiguTwo : function
2.1 System function
2.1.1 basename
1) Basic grammar
basename [string / pathname] [suffix] ( Function description :basename The command will delete all the previous
Including the last (‘/’) character , Then display the string .
basename It can be understood as taking the file name in the path
Options :
suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .
2) Case practice
Intercept this /home/atguigu/banzhang.txt File name of the path .
[[email protected] shells]$ basename /home/atguigu/banzhang.txt
banzhang.txt
[[email protected] shells]$ basename /home/atguigu/banzhang.txt .txt
banzhang
8.1.2 dirname
1) Basic grammar
dirname File absolute path ( Function description : Remove filename from given filename with absolute path ( Non catalog part ), Then return to the rest of the path ( Part of the catalog ))dirname It can be understood as the absolute path name of the file path
2) Case practice
obtain banzhang.txt Path to file .
[[email protected] ~]$ dirname /home/atguigu/banzhang.txt
/home/atguigu 2.2 Custom function
1) Basic grammar
[ function ] funname[()]
{
Action;
[return int;]
}2) Experience and skill
(1) Must be before calling function place , Declare function first ,shell The script is run line by line . Not like other languages
Sample compilation first .
(2) Function return value , Only through $? System variable acquisition , Can display plus :return return , If not , take
Run the result with the last command , As return value .return Heel value n(0-255)
3) Case practice
Calculate the sum of the two input parameters .
[[email protected] shells]$ touch fun.sh
[[email protected] shells]$ vim fun.sh
#!/bin/bash
function sum()
{
s=0
s=$[$1+$2]
echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
[atguigu[email protected] shells]$ chmod 777 fun.sh
[[email protected] shells]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
73、 ... and : Getting started with regular expressions
Regular expressions are described using a single string 、 Match a series of strings that conform to a certain syntax rule . In many articles
In this editor , Regular expressions are often used for retrieval 、 Replace the text that matches a pattern . stay Linux in ,grep,
sed,awk And other text processing tools support pattern matching through regular expressions .
3.1 Regular match
A string of regular expressions without special characters matches itself , for example :
[[email protected] shells]$ cat /etc/passwd | grep atguiguIt will match all that contain atguigu The line of .
3.2 Special characters are often used
1) Special characters :^
^ Match the beginning of a line , for example :
[[email protected] shells]$ cat /etc/passwd | grep ^aIt will match all of them with a Beginning line
2) Special characters :$
$ Match the end of a line , for example
[[email protected] shells]$ cat /etc/passwd | grep t$It will match all of them with t The line at the end
3) Special characters :.
. Match an arbitrary character , for example
[[email protected] shells]$ cat /etc/passwd | grep r..t Will match to include rabt,rbbt,rxdt,root And so on
4) Special characters :*
* Not used alone , He used it with the last character , Means to match the previous character 0 Times or times , for example
[[email protected] shells]$ cat /etc/passwd | grep ro*tWill match rt, rot, root, rooot, roooot Wait for all the lines
5) Character range ( brackets ):[ ]
[ ] Means to match a character in a range , for example
[6,8]------ matching 6 perhaps 8
[0-9]------ Match one 0-9 The number of
[0-9]*------ Matches any length of numeric string
[a-z]------ Match one a-z Characters between
[a-z]* ------ Matches an alphabetic string of any length
[a-c, e-f]- matching a-c perhaps e-f Any character between
[[email protected] shells]$ cat /etc/passwd | grep r[a,b,c]*t
Will match rt,rat, rbt, rabt, rbact,rabccbaaacbt Wait, all right
6) Special characters :\
\ To signify an escape , It will not be used alone . Because all special characters have their own matching patterns , When we want to match
When a particular character itself ( for example , I want to find out all the things that contain '$' The line of ), There will be difficulties . At this point we will
Use escape characters with special characters , To represent the special character itself , for example
[[email protected] shells]$ cat /etc/passwd | grep ‘a\$b’It will match all that contain a$b The line of . Note that you need to use single quotes to cause the expression to .
Four : Text processing tools
4.1 cut
cut The job of “ cut ”, Specifically, it is used to cut data in the file .cut Command from every part of the file
Cut bytes in one line 、 Characters and fields and put these bytes 、 Character and field output .
1) Basic usage
cut [ Option parameters ] filename
explain : The default separator is tab 2) Option parameter description

3) Case practice
(1) Data preparation
[[email protected] shells]$ touch cut.txt
[[email protected] shells]$ vim cut.txt
dong shen
guan zhen
wo wo
lai lai
le le
(2) cutting cut.txt First column
[[email protected] shells]$ cut -d " " -f 1 cut.txt
dong
guan
wo
lai
le
(3) cutting cut.txt second 、 The three column
[[email protected] shells]$ cut -d " " -f 2,3 cut.txt
shen
zhen
wo
lai
le
(4) stay cut.txt Cut out in file guan
[[email protected] shells]$ cat cut.txt |grep guan | cut -d " " -f 1
guan
(5) Selection system PATH A variable's value , The first 2 individual “:” All paths after start :
[[email protected] shells]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/atguigu/.local/bin:/
home/atguigu/bin
[[email protected] shells]$ echo $PATH | cut -d ":" -f 3-
/usr/local/sbin:/usr/sbin:/home/atguigu/.local/bin:/home/atguigu/bin
(6) cutting ifconfig Post print IP Address
[[email protected] shells]$ ifconfig ens33 | grep netmask | cut -d " " -f 10
192.168.111.1014.2 awk
A powerful text analysis tool , Read the document line by line , Slice each line with a space as the default separator , Cut open
Then analyze and deal with the part of .
1) Basic usage
awk [ Option parameters ] ‘/pattern1/{action1} /pattern2/{action2}...’ filename
pattern: Express awk What to look for in the data , It's a matching pattern
action: A series of commands executed when a match is found 2) Option parameter description

3) Case practice
(1) Data preparation
[[email protected] shells]$ sudo cp /etc/passwd ./
passwd What data means
user name : password ( Encrypted ): user id: Group id: notes : User home directory :shell Parser
(2) Search for passwd Document to root All lines at the beginning of the keyword , And output the 7 Column .
[[email protected] shells]$ awk -F : '/^root/{print $7}' passwd
/bin/bash
(3) Search for passwd Document to root All lines at the beginning of the keyword , And output the 1 Column and the first 7 Column ,
In the middle to “,” Division of no. .
[[email protected] shells]$ awk -F : '/^root/{print $1","$7}' passwd
root,/bin/bash
Be careful : Only match pattern Will be executed action.
(4) Display only /etc/passwd The first and seventh columns of , Comma separated , And add column names before all rows user,
shell Add on last line "dahaige,/bin/zuishuai".
[[email protected] shells]$ awk -F : 'BEGIN{print "user, shell"}
{print $1","$7}
END{print "dahaige,/bin/zuishuai"}' passwd
user, shell
root,/bin/bash
bin,/sbin/nologin ...
atguigu,/bin/bash
dahaige,/bin/zuishuai
Be careful :BEGIN Execute before all data read rows ;END Execute after all data execution .
(5) take passwd Users in files id Increase in numerical value 1 And the output
[[email protected] shells]$ awk -v i=1 -F : '{print $3+i}' passwd
1
2
3
44)awk Built in variables for

5) Case practice
(1) Statistics passwd file name , Line number of each line , Columns per row
[[email protected] shells]$ awk -F : '{print "filename:" FILENAME ",linenum:"
NR ",col:"NF}' passwd
filename:passwd,linenum:1,col:7
filename:passwd,linenum:2,col:7
filename:passwd,linenum:3,col:7
... (2) Inquire about ifconfig The line number of the empty line in the command output result
[[email protected] shells]$ ifconfig | awk '/^$/{print NR}'
9
18
26
(3) cutting IP
[[email protected] shells]$ ifconfig ens33 | awk '/netmask/ {print $2}'
192.168.6.1015、 ... and : Comprehensive application case
5.1 The archive
In practical production application , It is often necessary to archive and back up important data .
demand : Implement a script that archives and backs up the specified directory every day , Enter a directory name ( It doesn't end with /),
Archive and save all files in the directory on a daily basis , And attach the filing date to the file name , Put it in /root/archive Next .
The archive command is used here :tar
You can add -c Option means archive , add -z Option means to compress at the same time , The resulting file suffix is .tar.gz.
The script is implemented as follows :
#!/bin/bash
# First, judge whether the number of input parameters is 1
if [ $# -ne 1 ]
then
echo " Wrong number of parameters ! You should enter a parameter , As the archive directory name "
exit
fi
# Get the directory name from the parameter
if [ -d $1 ]
then
echo
else
echo
echo " directory does not exist !"
echo
exit
fi
DIR_NAME=$(basename $1)
DIR_PATH=$(cd $(dirname $1); pwd)
# Get current date
DATE=$(date +%y%m%d)
# Define the name of the generated archive file
FILE=archive_${DIR_NAME}_$DATE.tar.gz
DEST=/root/archive/$FILE
# Start archiving catalog files
echo " Start filing ..."
echo
tar -czf $DEST $DIR_PATH/$DIR_NAME
if [ $? -eq 0 ]
then
echo
echo " Archive success !"
echo " Archive file is :$DEST"
echo
else
echo " There is a problem with archiving !"
echo
fi
exit5.2 Send a message
We can use Linux Self contained mesg and write Tools , Send messages to other users .
demand : Implement a script to quickly send messages to a user , Enter the user name as the first parameter , Straight back
Follow the message to be sent . The script needs to detect whether the user logs in to the system 、 Whether to turn on the message function , And the current issue
Whether the sending message is empty .
The script is implemented as follows :
#!/bin/bash
login_user=$(who | grep -i -m 1 $1 | awk '{print $1}')
if [ -z $login_user ]
then
echo "$1 Not online !"
echo " Script exit .."
exit
fi
is_allowed=$(who -T | grep -i -m 1 $1 | awk '{print $2}')
if [ $is_allowed != "+" ]
then
echo "$1 No message function is enabled "
echo " Script exit .."
exit
fi
if [ -z $2 ]
then
echo " No message was sent "
echo " Script exit .."
exit
fi
whole_msg=$(echo $* | cut -d " " -f 2- )
user_terminal=$(who | grep -i -m 1 $1 | awk '{print $2}')
echo $whole_msg | write $login_user $user_terminal
if [ $? != 0 ]
then
echo " fail in send !"
else
echo " Send successfully !"
fi
exit边栏推荐
- What is WordPress
- Object to object mapping -automapper
- Ten thousand words detailed Google play online application standard package format AAB
- mysql还有哪些自带的函数呢?别到处找了,看这个就够了。
- ZBrush 2022软件安装包下载及安装教程
- LabVIEW AI视觉工具包(非NI Vision)下载与安装教程
- The fifth generation verification code of "cloud centered, insensitive and extremely fast" is coming heavily
- B2 sub theme / blog b2child sub theme / open source code
- R language - some metrics for unbalanced data sets
- No swagger, what do I use?
猜你喜欢

DHCP experiment demonstration (Huawei switch device configuration)

What kind of knowledge payment system functions are more conducive to the development of the platform and lecturers?

什么是WordPress
![[极客大挑战 2019]BabySQL-1|SQL注入](/img/21/b5b4727178a585e610d743e92248f7.png)
[极客大挑战 2019]BabySQL-1|SQL注入

ZBrush 2022 software installation package download and installation tutorial

服务器在线测速系统源码

Install SSL Certificate in Litespeed web server

What's the secret of creating a popular short video?

Open source huizhichuang future | 2022 open atom global open source summit openatom openeuler sub forum was successfully held

b2子主题/博客b2child子主题/开源源码
随机推荐
Can dynamic partitions be configured when MySQL is offline synchronized to ODPs
[MySQL] query multiple IDs and return string splicing
Understand how to prevent tampering and hijacking of device fingerprints
MySQL离线同步到odps的时候 可以配置动态分区吗
好用到爆!IDEA 版 Postman 面世了,功能真心强大
Xiaoshuidi 2.0 website navigation network template
Ten thousand words detailed Google play online application standard package format AAB
万字详解 Google Play 上架应用标准包格式 AAB
Iterative method for determinant (linear algebraic formula)
Object to object mapping -automapper
What is WordPress
mysql(8.0.16版)命令及说明
vim命令下显示行号[通俗易懂]
I want to ask you guys, if there is a master-slave switch when CDC collects mysql, is there any solution
【C语言】的%*d、%.*s等详解:「建议收藏」
Full version of H5 social chat platform source code [complete database + complete document tutorial]
目标检测领域必看的6篇论文
拥抱开源指南
用c语言编写学生成绩管理系统(c语言学生成绩管理系统删除)
CVPR2020 best paper:对称可变形三维物体的无监督学习