当前位置:网站首页>Shell script advanced
Shell script advanced
2022-04-23 08:24:00 【Programmer Ula】
Blogger introduction : Programmers understand ( Wula ~)
Personal warehouse : Code cloud
motto :“ lazy ” How devastating is it to a person , How important it is to get up early .
disclaimer : The article was created by the blogger 、 Some articles are arranged on the Internet , For learning and knowledge sharing only
Meeting is fate , Now that you're here, carry a small bench 🪑 Sit down and talk for a while , If you gain something in this article , Please don't forget to click three times , Use your little hand to get rich , Your encouragement , It's the driving force of my creation !
List of articles
Shell Script advanced
One 、 To choice 、 Judge
1、 To choice if
if Judge the condition 1 ; then
Branch code with true condition
elif Judge the condition 2 ; then
Branch code with true condition
elif Judge the condition 3 ; then
Branch code with true condition
else
All of the above conditions are false branch codes
fi
Judge by conditions , First encounter “ really ” When the conditions , Take its branches , And then end the whole if.
Case study 1
# Judge age
#!/bin/bash
read -p "Please input your age: " age
if [[ $age =~ [^0-9] ]] ;then
echo "please input a int"
exit 10
elif [ $age -ge 150 ];then
echo "your age is wrong"
exit 20
elif [ $age -gt 18 ];then
echo "good good work,day day up"
else
echo "good good study,day day up"
fi
analysis : Please enter age , First determine whether the input contains characters other than numbers , Yes , Just report a mistake ; No, , Continue to judge if it is less than 150, Is it greater than 18.
Case list 2
# Judge the score
#!/bin/bash
read -p "Please input your score: " score
if [[ $score =~ [^0-9] ]] ;then
echo "please input a int"
exit 10
elif [ $score -gt 100 ];then
echo "Your score is wrong"
exit 20
elif [ $score -ge 85 ];then
echo "Your score is very good"
elif [ $score -ge 60 ];then
echo "Your score is soso"
else
echo "You are loser"
fi
analysis : Please enter the grade , First determine whether the input contains characters other than numbers , Yes , Just report a mistake ; No, , Continue to judge whether it is greater than 100, Is it greater than 85, Is it greater than 6.
2、 conditional case
case $name in;
PART1)
cmd
;;
PART2)
cmd
;;
*)
cmd
;;
esac
-
Be careful :case Support glob Style wildcard :
-
Any length, any character
?: Any single character
[] : Any single character in the specified range
a|b: a or b
Case list 1
# Judge yes or no
#!/bin/bash
read -p "Please input yes or no: " anw
case $anw in
[yY][eE][sS]|[yY])
echo yes
;;
[nN][oO]|[nN])
echo no
;;
*)
echo false
;;
esac
analysis : Please enter yes or no, answer Y/y、yes The various case combinations are yes; answer N/n、No The various case combinations are no.
Two 、 Four cycles
1、for
① for name in list ;do
The loop body
done
② for (( exp1; exp2; exp3 )) ;do
cmd
done
exp1 Only once , Equivalent to the for It's embedded in the wall while.
③ Execution mechanism :
- Assign elements in the list to “ Variable name ”; The loop body is executed once after each assignment ; Until the elements in the list are exhausted , The loop ends
- The representation of a list , Sure glob wildcard , Such as {1…10} 、*.sh ; You can also refer to variables , Such as :
seq 1 $name
Case study 1
# Find out (1+2+...+n) The sum of
sum=0
read -p "Please input a positive integer: " num
if [[ $num =~ [^0-9] ]] ;then
echo "input error"
elif [[ $num -eq 0 ]] ;then
echo "input error"
else
for i in `seq 1 $num` ;do
sum=$[$sum+$i]
done
echo $sum
fi
unset zhi
analysis :sum The initial value is 0, Please enter a number , First determine whether the input contains characters other than numbers , Yes , Just report a mistake ; There is no judgment whether it is 0, Not for 0 Get into for loop ,i For the range of 1~ Number of inputs , Each cycle is sum=sum+i, The loop ends , The final output sum Value .
Case list 2
# Find out (1+2+...+100) The sum of
for (( i=1,num=0;i<=100;i++ ));do
[ $[i%2] -eq 1 ] && let sum+=i
done
echo sum=$sum
analysis :i=1,num=0; When i<=100, Into the loop , if i÷2 Remainder =1, be sum=sum+i,i=i+1.
2、while
while Cycle control conditions ;do
loop
done
Cycle control conditions ; Before entering the cycle , Make a judgment first ; After each cycle, the judgment will be made again ; Condition is “true” , Then execute a cycle ; Until the condition test status is “false” End cycle .
Special Usage ( Traverse every line of the file )
while read line; do Control variable initialization
The loop body
done < /PATH/FROM/SOMEFILE
or cat /PATH/FROM/SOMEFILE | while read line; do
The loop body
done
Read... In turn /PATH/FROM/SOMEFILE Every line in the file , And assign the row to the variable line.
Case list 1
#100 The sum of all positive odd numbers within
sum=0
i=1
while [ $i -le 100 ] ;do
if [ $[$i%2] -ne 0 ];then
let sum+=i
let i++
else
let i++
fi
done
echo "sum is $sum"
analysis :sum The initial value is 0,i The initial value of 1; Please enter a number , First determine whether the input contains characters other than numbers , Yes , Just report a mistake ; Not when i<100 when , Into the loop , Judge i÷2 Remainder If not for 0, Not for 0 Time is odd ,sum=sum+i,i+1, by 0,i+1; The loop ends , The final output sum Value .
3、until loop
unitl The loop condition ;do
loop
done
Entry conditions : The cycle condition is true ; Exit conditions : The cycle condition is false; Just in time with while contrary , So not often , use while Just go .
Case list 1
# monitor dsjprs user , Log in and kill
until pgrep -u dsjprs &> /dev/null ;do
sleep 0.5
done
pkill -9 -u dsjprs
analysis : every other 0.5 Second scan , Until I found out dsjprs The user login , Kill the process , Exit script , Used to monitor user login .
4、select Loops and menus
select variable in list
do
Loop body command
done
① select Loops are mainly used to create menus , The menu items in numerical order will be displayed on standard error , And display PS3 Prompt , Waiting for user input
② The user enters a number in the menu list , Execute the corresponding command
③ User input is saved in built-in variables REPLY in
④ select It's an infinite loop , So remember to use break Command to exit the loop , Or use exit Press Command to terminate the script . You can also press ctrl+c Exit loop
⑤ select and Often with case A combination of
⑥ And for Circulation similar , It can be omitted in list, In this case, the position parameter is used
Case list 1
# generate menu , And display the selected price
PS3="Please choose the menu: "
select menu in mifan huimian jiaozi babaozhou quit
do
case $REPLY in
1|4)
echo "the price is 15"
;;
2|3)
echo "the price is 20"
;;
5)
break
;;
*)
echo "no the option"
esac
done
analysis :PS3 yes select Prompt , Automatically generate menus , choice 5break Exit loop .
3、 ... and 、 Some usage in circulation
1、 Loop control statement
continue [N]: Finish the second N This cycle of layers , And go straight to the next round of judgment ; The innermost layer is 1 layer
break [N]: Finish the second N Layer cycle , The innermost part is 1 layer
example :while CONDTITON1; do
CMD1
if CONDITION2; then
continue / break
fi
CMD2
done
Case list 1
#① seek (1+3+...+49+53+...+100) And
#!/bin/bash
sum=0
for i in {
1..100} ;do
[ $i -eq 51 ] && continue
[ $[$i%2] -eq 1 ] && {
let sum+=i;let i++; }
done
echo sum=$sum
analysis : do 1+2+…+100 The cycle of , When i=51 when , Skip this cycle , But continue the whole cycle , The result is :sum=2449
Case list 2
#② seek (1+3+...+49) And
#!/bin/bash
sum=0
for i in {
1..100} ;do
[ $i -eq 51 ] && break
[ $[$i%2] -eq 1 ] && {
let sum+=i;let i++; }
done
echo sum=$sum
analysis : do 1+2+…+100 The cycle of , When i=51 when , Out of the loop , The result is :sum=625
2、 Cycle control shift command
effect
It is used to set the parameter list list Move left a specified number of times , The leftmost parameter is removed from the list , The next parameter continues to enter the loop
Case list 1
#① Create a specified number of users
#!/binbash
if [ $# -eq 0 ] ;then
echo "Please input a arg(eg:`basename $0` arg1)"
exit 1
else
while [ -n "$1" ];do
useradd $1 &> /dev/null
shift
done
fi
analysis : If there are no input parameters ( The total number of parameters is 0), Prompt for errors and exit ; conversely , Into the loop ; If the first parameter is not a null character , Then create a user named after the first parameter , And remove the first parameter , Move the following parameter to the left as the first parameter , Until there's no first parameter , sign out .
Case list 2
#② Print right triangle characters
#!/binbash
while (( $# > 0 ))
do
echo "$*"
shift
done
3、 Return value result
true Always return to success
: null command , Do nothing , Return the successful result
false Always return the wrong result
Create infinite loops
while true ;do
The loop body
done
4、 The loop can be executed in parallel , Make scripts run faster
for name in list ;do
{
The loop body
}&
done
wait
Case list 1
# Search your own designated ip( The subnet mask is 24 Of ) In segments of ,UP Of ip Address
read -p "Please input network (eg:192.168.0.0): " net
echo $net |egrep -o "\<(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>"
[ $? -eq 0 ] || ( echo "input error";exit 10 )
IP=`echo $net |egrep -o "^([0-9]{1,3}\.){3}"`
for i in {
1..254};do
{
ping -c 1 -w 1 $IP$i &> /dev/null && \
echo "$IP$i is up"
}&
done
wait
analysis : Please enter a IP Address example 192.168.37.234, If the format is not 0.0.0.0 Then report an error and exit ; Right goes into the cycle ,IP The value of the variable is 192.168.37. i For the range of 1-254, parallel ping 192.168.37.1-154,ping This is the output IP by UP. Until the end of the cycle .
Four 、 Signal acquisition trap
trap ' Trigger command ' The signal , After the custom process receives the specified signal from the system , The trigger command will be executed , Instead of performing the original operation
trap '' The signal , Ignore the operation of the signal
trap '-' The signal , The operation of restoring the original signal
trap -p, List custom signal operations
The signal can 3 There are two ways to express : The number of signals 2、 full name SIGINT、 abbreviation INT
Common signals :
1) SIGHUP: Reread the configuration file without shutting down the process
2) SIGINT: Abort a running process ; amount to Ctrl+c
3) SIGQUIT: amount to ctrl+\
9) SIGKILL: Force to kill a running process
15) SIGTERM : Terminate a running process ( The default is 15)
18) SIGCONT : Continue operation
19) SIGSTOP : Background sleep
9 The signal , Force to kill , I can't catch it
Case list 1
#① Print 0-9,ctrl+c Cannot terminate
#!/bin/bash
trap 'echo press ctrl+c' 2
for ((i=0;i<10;i++));do
sleep 1
echo $i
done
analysis :i=0, When i<10, Every sleep 1 second ,i+1, Capture 2 The signal , And implement echo press ctrl+c
Case list 2
#② Print 0-3,ctrl+c Cannot terminate ,3 Then recover , Can stop
#!/bin/bash
trap '' 2
trap -p
for ((i=0;i<3;i++));do
sleep 1
echo $i
done
trap '-' SIGINT
for ((i=3;i<10;i++));do
sleep 1
echo $i
done
analysis :i=0, When i<3, Every sleep 1 second ,i+1, Capture 2 The signal ;i>3 when , Release capture 2 The signal .
5、 ... and 、 Script knowledge
1、 Generate random characters cat /dev/urandom
# Generate 8 A random case letter or number
cat /dev/urandom |tr -dc [:alnum:] |head -c 8
2、 Generate random number echo $RANDOM
Determine scope echo $[RANDOM%7] Random 7 Number (0-6)
echo $[$[RANDOM%7]+31] Random 7 Number (31-37)
3、echo Print color words
echo -e "\033[31malong\033[0m" Show red along
echo -e "\033[1;31malong\033[0m" Highlight red along
echo -e "\033[41malong\033[0m" The background color of the display is red along
echo -e "\033[31;5malong\033[0m" It's flashing red along
color=$[$[RANDOM%7]+31]
echo -ne "\033[1;${color};5m*\033[0m" Show flashing random colors along
6、 ... and 、 significant Shell Script
1、9x9 Multiplication table
#!/bin/bash
for a in {
1..9};do
for b in `seq 1 $a`;do
let c=$a*$b ;echo -e "${a}x${b}=$c\t\c"
done
echo
done
2、 Color isosceles triangle
#!/bin/bash
read -p "Please input a num: " num
if [[ $num =~ [^0-9] ]];then
echo "input error"
else
for i in `seq 1 $num` ;do
xing=$[2*$i-1]
for j in `seq 1 $[$num-$i]`;do
echo -ne " "
done
for k in `seq 1 $xing`;do
color=$[$[RANDOM%7]+31]
echo -ne "\033[1;${color};5m*\033[0m"
done
echo
done
fi
3、 chess board
#!/bin/bash
red="\033[1;41m \033[0m"
yellow="\033[1;43m \033[0m"
for i in {
1..8};do
if [ $[i%2] -eq 0 ];then
for i in {
1..4};do
echo -e -n "$red$yellow";
done
echo
else
for i in {
1..4};do
echo -e -n "$yellow$red";
done
echo
fi
done
If you gain something in the article , Please thumb up + Focus on , Traditional virtues cannot be lost
版权声明
本文为[Programmer Ula]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230743174092.html
边栏推荐
猜你喜欢
Somme numérique de la chaîne de calcul pour un problème simple de leetcode
CGM优化血糖监测管理——移宇科技亮相四川省国际医学交流促进会
An article understands variable lifting
The third divisor of leetcode simple question
LeetCode簡單題之計算字符串的數字和
My heart's broken! A woman's circle of friends envied others for paying wages on time and was fired. Even her colleagues who liked her were fired together
Search the complete navigation program source code
总线结构概述
分布式消息中间件框架选型-数字化架构设计(7)
PyQt5开发之QTableWidget表头自定义与美化(附源代码下载)
随机推荐
让地球少些“碳”息 度能在路上
ansible自動化運維詳解(一)ansible的安裝部署、參數使用、清單管理、配置文件參數及用戶級ansible操作環境構建
ansible自动化运维详解(一)ansible的安装部署、参数使用、清单管理、配置文件参数及用户级ansible操作环境构建
JS converts tree structure data into one-dimensional array data
[effective go Chinese translation] part I
Compiler des questions de principe - avec des réponses
有意思的js 代码
WordPress爱导航主题 1.1.3 简约大气网站导航源码网址导航源码
A simple theme of Typecho with beautiful appearance_ Scarfskin source code download
扎心了!一女子发朋友圈羡慕别人按时发工资被开除,连点赞的同事也一同被开除了...
QT reading and writing XML files
Common regular expressions
Kubernetes in browser and IDE | interactive learning platform killercoda
Compiling principle questions - with answers
npm安装yarn
The simple problem of leetcode is to calculate the numerical sum of strings
Online app resource download website source code
Flink SQL实现流批一体
Vowel substring in statistical string of leetcode simple problem
怎么读书读论文