shell第四天正则

正则

正则分为基础正则扩展正则
正则

表达式 解释 示范
. 匹配任意单个字符(必须存在) "ro.t"可以是root,roat。"r…t"可以是root,raet
^ 表示以什么开头 “^#” 匹配以#开头的行
$ 表示以什么结尾 “root$” 表示匹配以root结尾的行
* 匹配前一个字符的一个或多个 可以为0 “a*b” 可以是aab,aaab,b,aaaab
.* 表示匹配任意长度的字符 “.*t” 可以是root,boot,beat,以t结尾的
[] 表示范围的一个字符 [0-9]匹配数字,[a-z]匹配小写,[abc]匹配abc三个字符的任意一个
[^] 表示不再范围的一个字符,与[]相反 [^0-9]不匹配数字
^[^] 匹配不在[]范围里的字符为开头的字符 ^[^A-Z] 表示匹配不以大写字母开头的字符
{n} 匹配前面字符至少n个字符 a{2}表示aaa aaaa aaaaa
{n,m} 匹配前面字符至少n个字符,最多m个字符 a{2,4}为aaa,aaaa,aaaaa
() 分组
< 锁定单词开头 <r 表示单词开头必须是r ,root,read
> 锁定单词结尾 t>表示单词结尾必须是t ,root,about

函数

格式
函数名 () {

commands

}
例:写一个名叫hello_world的函数,要求输出hello world

[root@compute ~]# vim test1.sh  
#!/bin/bash
hello_world () {
        echo "hello world"
}
hello_world   #调用函数
[root@compute ~]# bash test1.sh 
hello world

函数里面定义参数跟平时一样,但是传入参数不是在脚本外面传,而是在调用函数后面传入
例:

[root@compute ~]# vim test1.sh 
#!/bin/bash
hello_world () {
        echo "hello world"
        echo $1
}
hello_world hello  #传入参数hello
[root@compute ~]# bash test1.sh 
hello world
hello

函数里面也可以定义返回值,return定义返回值,并终止函数

[root@compute ~]# vim test1.sh  
#!/bin/bash
hello_world () {
        echo "hello world"
        echo $1
        return 2   
        echo "test"  #运行到return函数终止,所以这里无意义
}
hello_world hello
echo $?     #函数返回值用$?查看
[root@compute ~]# bash test1.sh 
hello world
hello
2
发布了10 篇原创文章 · 获赞 4 · 访问量 1590

猜你喜欢

转载自blog.csdn.net/qq_32502263/article/details/104412713