分支用于无条件转移,测试用于有条件转移
分支 branch
跳转的位置与标签相关联
如果有标签则跳转到标签所在的后面行继续执行
如果没有标签则跳转到脚本的结尾处
标签 以冒号开始后接标签名,不要在标签名前后使用空格
跳转到标签指定位置
[root@localhost test]# grep myuser /etc/passwd
myuser:x:501:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser /etc/passwd|sed ':top;s/myuser/WUWEI/;/myuser/b top;s/5/66/'
WUWEI:x:6601:501::/home/WUWEI:/bin/bash
命令分析:
[root@localhost test]# grep myuser /etc/passwd | sed '
:top; //设置标签
s/myuser/WUWEI/; //将第一个myuser替换为WUWEI
/myuser/b top; //如果匹配到有myuser,则跳转到标签top处
s/5/66/g' //当上一条不匹配时,执行本语句将5替换为66
选择执行一:
[root@localhost test]# grep myuser /etc/passwd|sed 's/myuser/WUWEI/;/myuser/b end;s/5/66/;:end;s/5/77/'
WUWEI:x:7701:501::/home/myuser:/bin/bash
命令分析:执行cmd1命令,再去匹配模式,如果匹配成功则跳转到标签end后执行cmd3命令,否则会按命令顺序逐个执行cmd2和cmd3.
[root@localhost test]# grep myuser /etc/passwd|sed '
s/myuser/WUWEI/; cmd1
/myuser/b end;
s/5/66/; cmd2
:end;
s/5/77/' cmd3
选择执行二:
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;/myuser/b end;s/5/66/;b;:end;s/5/77/' //模式匹配成功类型
WUWEI:x:7701:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;/myuser11/b end;s/5/66/;b;:end;s/5/77/' //模式匹配失败类型
WUWEI:x:6601:501::/home/myuser:/bin/bash
命令分析:先执行cmd1命令;再进行模式匹配,如果匹配成功则跳转到end标签后执行cmd3命令,否则执行cmd2命令,再跳转到脚本末尾
[root@localhost test]# grep myuser passwd |sed '
s/myuser/WUWEI/; cmd1
/myuser/b end;
s/5/66/; cmd2
b;
:end;
s/5/77/' cmd3
-----------------------
测试命令,如果前一个替换命令执行成功则跳转到脚本末尾
测试示例:
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;t;s/home/HOME/;t;s/bash/BASH/'
WUWEI:x:501:501::/home/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/AAmyuser/WUWEI/;t;s/home/HOME/;t;s/bash/BASH/'
myuser:x:501:501::/HOME/myuser:/bin/bash
[root@localhost test]# grep myuser passwd |sed 's/AAmyuser/WUWEI/;t;s/AAhome/HOME/;t;s/bash/BASH/'
myuser:x:501:501::/home/myuser:/bin/BASH
命令分析:如果cmd1命令执行成功,则跳到脚本末尾,如果cmd1命令执行不成,匹配执行cmd2命令,如果cmd2能执行成功,则跳转到脚本末尾;否则匹配cmd3能否执行成功
[root@localhost test]# grep myuser passwd |sed '
s/myuser/WUWEI/; cmd1
t;
s/home/HOME/; cmd2
t;
s/bash/BASH/' cmd3
与标签关联,跳转到指定标签位置
[root@localhost test]# grep myuser passwd |sed 's/myuser/WUWEI/;t end;s/home/HOME/;t;:end;s/bash/BASH/'
WUWEI:x:501:501::/home/myuser:/bin/BASH
命令分析:如果cmd1命令执行成功,则跳转到end标签后面执行cmd3,否则匹配cmd2是否能执行成功,如果成功,则跳转到脚本末尾,否则继续匹配cmd3命令能否执行成功
[root@localhost test]# grep myuser passwd |sed '
s/myuser/WUWEI/; cmd1
t end;
s/home/HOME/; cmd2
t;
:end;
s/bash/BASH/' cmd3