当前位置:网站首页>Learn shell script (5) -- function, random number, regular expression
Learn shell script (5) -- function, random number, regular expression
2022-04-22 13:14:00 【Xiao Wang's note warehouse】
One . function
shell Will be allowed in A set of commands or sentence Form a section Available code , These blocks of code are called shell function . Give this code a name called function name , You can call the function of this code directly later .
1. Function definition
Function name ()
{
The body of the function ( A collection of orders , To achieve a function )
}
# You can take function Function name () Definition , It can also be direct Function name () Definition , Without any parameters
function Function name ()
{
The body of the function ( A collection of orders , To achieve a function )
}
· return explain :
1.return You can end up with a function , Similar to the loop control statement mentioned earlier break.
2.return The default returns the exit status of the last command in the function , You can also give parameter values , The value range of this parameter is 0-256 Between .
3. without return command , The function will return the last Shell The exit value of .
2. Function call
2.1 Called directly in script
#!/bin/bash
demoFun()
{
echo " This is a shell function !"
}
echo "----- The function starts executing -----"
demoFun
echo "----- The function is finished -----"
2.2 Defined in the user's environment variables
# When the user opens bash The file will be read when :
/etc/profile --> /etc/bashrc --> ~/.bash_profile --> ~/.bashrc
# We can directly define functions in these files to call
2.3 Current command line call
[root@server ~]# cat test.sh
#!/bin/bash
demoFun()
{
echo " This is a shell function !"
}
[root@server ~]# source test.sh
[root@server ~]# demoFun
This is a shell function !
3. Function arguments
#!/bin/bash
funWithParam()
{
echo " The first parameter is zero $1 !"
echo " The second parameter is $2 !"
echo " The tenth parameter is $10 !"
echo " The tenth parameter is ${10} !"
echo " The eleventh parameter is ${11} !"
echo " The total number of parameters is $# individual !"
echo " Output all parameters as a string $* !"
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
# stay Shell in , You can pass parameters to a function when you call it .
# Inside the body of the function , adopt $n To get the value of the parameter
Case study : Let users enter information , If you don't enter, keep prompting until you enter
#!/bin/bash
input_fun()
{
input_var=""
output_var=$1
while [ -z $input_var ]
do
read -p "$output_var" input_var
done
echo $input_var
}
# Call the function and get the user's name 、 Gender 、 Age is assigned to name、sex、age Variable
name=$(input_fun Please enter your name :)
sex=$(input_fun Please enter your gender :)
age=$(input_fun Please enter your age :)
#!/bin/bash
input_fun()
{
read -p "$1" name
if [ -z $name ];then
fun $1
else
echo $name
fi
}
# Call the function and get the user's name 、 Gender 、 Age is assigned to name、sex、age Variable
name=$(input_fun Please enter your name :)
sex=$(input_fun Please enter your gender :)
age=$(input_fun Please enter your age :)
Two . random number
1. Grammatical structure
# bash There is one by default $RANDOM The variable of , The default is 0~32767.
set | grep RANDOM
# Check the last generated random number
echo $RANDOM
# produce 0~1 Random number between
echo $[$RANDOM%2]
# produce 0~9 The random number in
echo $[$RANDOM%10]
# produce 0~100 The random number in
echo $[$RANDOM%101]
# produce 50-100 A random number within
echo $[$RANDOM%51+50]
# To produce a three digit random number
echo $[$RANDOM%900+100]
2. Case study
1) Randomly generated 1000 In a 182 Cell phone number at the beginning
#!/bin/bash
for ((i=1;i<=1000;i++))
do
n1=$[$RANDOM%10]
n2=$[$RANDOM%10]
n3=$[$RANDOM%10]
n4=$[$RANDOM%10]
n5=$[$RANDOM%10]
n6=$[$RANDOM%10]
n7=$[$RANDOM%10]
n8=$[$RANDOM%10]
echo "182$n1$n2$n3$n4$n5$n6$n7$n8" |tee -a phonenum.txt
done
2) Draw lucky viewers
# Above 1000 Lottery in a cell phone number 5 A lucky audience .
# It shows that 5 A lucky audience .
# Show only headers 3 Number and tail number 4 Number , Intermediate use * Instead of .
#!/bin/bash
phone=phonenum.txt
for ((i=1;i<=5;i++))
do
# Count the number of lines of file content
num=`wc -l phonenum.txt |cut -d' ' -f1`
# Randomly select one of the rows
luck_line=`echo $[$RANDOM%$num+1]`
# Take out the lucky line
luck_person=`head -$luck_line $phone |tail -1`
# Delete the lucky user in the source file , Avoid secondary extraction
sed -i "/$luck_person/d" $phone
echo " The lucky audience is :182****${luck_person:7:4}"
done
3) Batch creation 5 Users , Each user's password is a random number
#!/bin/bash
# Generate a file to save the user name and password ( Four random numbers )
echo user{
1..3}:wang$[$RANDOM%9000+1000] | tr ' ' '\n'>> user_pass.file
# echo user{1..3}:$(pwgen -cn1 12)|tr ' ' '\n'
for ((i=1;i<=5;i++))
do
user=`head -$i user_pass.file|tail -1|cut -d: -f1`
pass=`head -$i user_pass.file|tail -1|cut -d: -f2`
useradd $user
echo $pass|passwd --stdin $user
done
#!/bin/bash
# Generate a file to save the user name and password ( Four random numbers )
echo user{
1..3}:wang$[$RANDOM%9000+1000] | tr ' ' '\n'>> user_pass.file
# echo user0{1..3}:$(pwgen -cn1 12)|tr ' ' '\n'
for i in `cat user_pass.file`
do
user=`echo $i|cut -d: -f1`
pass=`echo $i|cut -d: -f2`
useradd $user
echo $pass|passwd --stdin $user
done
3、 ... and . Regular expressions
Regular expressions , Also known as regular expression .( English :Regular Expression, In code it is often abbreviated as regex、regexp or RE), A concept of computer science . Regular expressions are often used for retrieval 、 Replace those that match a pattern ( The rules ) The text of .
Many programming languages support string manipulation with regular expressions . for example , stay Perl A powerful regular expression engine is built in .
The concept of regular expression was originally developed by Unix Tool software in ( for example sed and grep) Popular . Support regular expression programs such as :find,vim,grep,sed,awk
- For details of regular expressions, you can refer to Novice tutorial
- 70 Collation and summary of regular expressions
| Metacharacters | describe | Example |
|---|---|---|
| \ | Escape character , Escape special characters , Ignore its special significance | a.b matching a.b, But can't match ajb,. Be escaped as a special meaning |
| ^ | Match the beginning of the line ,awk in ,^ Is the beginning of the matching string | ^tux Match with tux Beginning line |
| $ | Match the end of the line ,awk in ,$ Is the end of the matching string | tux$ Match with tux The line at the end |
| . | Match break \n Any single character other than | ab. matching abc or bad, Unmatched abcd or abde, Only single characters can be matched |
| [ ] | Match included in [ character ] Any one of the characters | coo[kl] Can match cook or cool |
| [^] | matching [^ character ] Any character other than | 123[^45] Can't match 1234 or 1235,1236、1237 Fine |
| [-] | matching [] Any character within the specified range in , Write it in increments | [0-9] Can match 1、2 or 3 Wait for any number |
| ? | Match previous items 1 Time or 0 Time | colou?r Can match color perhaps colour, Can't match colouur |
| + | Match previous items 1 Times or more | sa-6+ matching sa-6、sa-666, Can't match sa- |
| * | Match previous items 0 Times or more | co*l matching cl、col、cool、coool etc. |
| () | Match expression , Create a substring for matching | ma(tri)? matching max or maxtrix |
| {n} | Match previous items n Time ,n Can be for 0 The positive integer | [0-9]{3} Match any three digits , It can be extended to [0-9][0-9][0-9] |
| {n,} | Previous items need to match at least n Time | [0-9]{2,} Matching any two or more digits is not supported {n,}{n,}{n,} |
| {n,m} | Specify that the previous item matches at least n Time , Match at most m Time ,n<=m | [0-9]{2,5} Match any number from two to five digits |
| | | Alternate matching | Either of the two sides | ab(c|d) matching abc or abd |
Four . Add
1.shift
shift: Move the position parameter to the left , Default move 1 position
#!/bin/bash
# This script can realize Add the sum of all parameters after the script
sum=0
while [ $# -ne 0 ]
do
let sum=$sum+$1
shift
done
echo sum=$sum
2.expect Auto answer
#!/usr/bin/expect
# Set a variable
set ip 10.1.1.1
set pass 123456
set timeout 5
#spawn Is to add a shell to the later running process , Used to pass interactive instructions
spawn ssh root@$ip
#expect It is used to judge whether the last output result in the interaction contains some strings
expect {
#exp_continue Attach to a expect After the judgment , After matching this item, continue to match other items
"yes/no" {
send "yes\r";exp_continue }
"password:" {
send "$pass\r" }
}
expect "#"
#send Used to perform interactive actions , Equivalent to manual input
send "rm -rf /tmp/*\r"
send "touch /tmp/file{1..3}\r"
send "date\r"
send "exit\r"
expect eof
版权声明
本文为[Xiao Wang's note warehouse]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221311051398.html
边栏推荐
- Explain in detail why the number of pixels with a gray value of 255 calculated by the opencv histogram calculation function calchist() is 0
- MySQL 使用存储过程添加数据
- ROS2——参数的使用
- CubeMX配置SPI-Flash(W25Q256)
- Walking in the clouds - but there are books
- Type requirements for parameters pT1 and pT2 of OpenCV function line()
- The compatibility certification of ecological Wanli database and Yixin technology has been completed
- Mysql database has been started successfully, but show is not an internal or external command. How to solve it?
- rsync远程同步
- 我们需要什么样的数据库产品
猜你喜欢

ROS机器人学习——麦克纳姆轮运动学解算

Digital business cloud electronic bidding system solution - standardize the political procurement process and improve work efficiency

Redis的下载安装

Oracle NetSuite 客户说 | 让中影巴可流程控制更精细的“核心秘籍”

RT-Thread配置SPI-Flash(W25Q256)

Digital commerce cloud centralized procurement system: centralized procurement and internal and external collaboration to minimize abnormal expenses

R语言绘制小提琴图geom_violin,如何添加额外的点geom_point?geom_violin + geom_boxplot + geom_point组合使用
![[introduction to keras] MNIST dataset classification](/img/8f/1f9f8674c3212223af85eaec3a34f0.png)
[introduction to keras] MNIST dataset classification

Sprint strategy for soft test preparation in the first half of 2022

柔性印刷电路板(PCB)的设计方法、类型等详细解析
随机推荐
The compatibility certification of ecological Wanli database and Yixin technology has been completed
上市公司营业收入数据集(1990-2021第三季度)
最大匹配数,最小路径覆盖数,最大独立数,最小点覆盖数 定理总结
Corners of enterprise mailbox
OPLG:新一代云原生可观测最佳实践
Compressed backup of raspberry pie
稻盛和夫:直面现实、拼命思考、正面迎击
HDU 2680 最短路 Dijkstra + 链式向前星 + 优先队列(模板)
MapReduce案例—分别通过Reduce端和Map端实现JOIN操作
Altium Designer导出Gerber文件的一般步骤
R language uses dhyper function to generate hypergeometric distribution density data and plot function to visualize hypergeometric distribution density data
深度学习论文阅读目标检测篇(二):Fast R-CNN《Fast R-CNN》
Rsync remote synchronization
各省GTFP绿色全要素生产率面板数据(2004-2018年)
ORA-1652 无法扩展TEMP表空间
各省GTFP綠色全要素生產率面板數據(2004-2018年)
Redis如何查看单个key所占用的内存大小
Données du panel sur la productivité verte totale des facteurs du pfgt par province (2004 - 2018)
Redis local connection to view data
Oplg: new generation cloud primary observable best practices