linux 系统sheel脚本中多条命令串行运算时如何保证前一条正确运算再运行下一条命令

 

linux 系统sheel脚本中多条命令串行运算时如何保证前一条正确运算再运行下一条命令

 

001、默认情况

[root@PC1 test01]# ls
test.sh
[root@PC1 test01]# cat test.sh            ## 测试脚本, 其中1和3是正确命令;2是错误命令
#!/usr/bin/env bash

echo hello world > a.txt

xxx > b.txt

seq 3 > c.txt

[root@PC1 test01]# bash test.sh          ## 执行脚本
test.sh: line 5: xxx: command not found
[root@PC1 test01]# ls                    ## 尽管第二条命令是失败的,默认仍然运算了第三条命令
a.txt  b.txt  c.txt  test.sh
[root@PC1 test01]# cat a.txt
hello world
[root@PC1 test01]# cat b.txt
[root@PC1 test01]# cat c.txt
1
2
3

image

 。

 

002、保证前一条命令正确运算后再运行下一条命令:增加set -e

[root@PC1 test01]# ls
test.sh
[root@PC1 test01]# cat test.sh    ## 测试脚本;增加了set -e
#!/usr/bin/env bash
set -e

echo hello world > a.txt

xxx > b.txt

seq 3 > c.txt
[root@PC1 test01]# bash test.sh            ## 执行程序
test.sh: line 6: xxx: command not found
[root@PC1 test01]# ls                      ## 第二条是错误命令,不继续运行第三条命令
a.txt  b.txt  test.sh
[root@PC1 test01]# cat a.txt
hello world
[root@PC1 test01]# cat b.txt

image

。 

 

posted @ 2026-01-27 09:45  小鲨鱼2018  阅读(0)  评论(0)    收藏  举报