shell编程之十(脚本中 set -e、set -u 、set -o pipefail 的作用)

set 命令参数意思

# set 命令参数意思
    set -e          # 表示一旦脚本中有命令的返回值为非0,则脚本立即退出,后续命令不再执行;
    set -u          # 当脚本中使用未定义的变量时,立即退出并报错。这可以防止意外使用未初始化的变量,从而减少潜在的 bug
    set -o pipefail # 表示在管道连接的命令序列中,只要有任何一个命令返回非0值,则整个管道返回非0值,即使最后一个命令返回0.(知识虽小,但是很有用)

案例一(测试set -e)

+++++++++++++++++++++++++
# 未使用 set -e前
[root@localhost ~]# cat a.sh 
#!/bin/bash
set -x
echo "你好"
cat /oo.txt
echo "你好呀"

    # 执行情况
[root@localhost ~]# ./a.sh 
+ echo 你好
你好
+ cat /oo.txt
cat: /oo.txt: No such file or directory
+ echo 你好呀
你好呀

+++++++++++++++++++++++
# 使用set -e 后
[root@localhost ~]# cat a.sh 
#!/bin/bash
set -xe
echo "你好"
cat /oo.txt
echo "你好呀"

    # 执行情况
[root@localhost ~]# cat a.sh 
#!/bin/bash
set -xe
echo "你好"
cat /oo.txt
echo "你好呀"
[root@localhost ~]# ./a.sh 
+ echo 你好
你好
+ cat /oo.txt
cat: /oo.txt: No such file or directory

案例2(测试 set -o pipefail)

#################脚本内容
#!/bin/bash
# 定义一个总是失败的命令
command1() {
  echo "Running command1"
  return 1
}
# 定义一个总是成功的命令
command2() {
  echo "Running command2"
  return 0
}
# 不使用 set -o pipefail
echo "Without set -o pipefail"
command1 | command2
echo "Exit status: $?"
# 使用 set -o pipefail
echo "With set -o pipefail"
set -o pipefail
command1 | command2
echo "Exit status: $?"
###################执行结果

Without set -o pipefail
Running command2
Exit status: 0
With set -o pipefail
Running command2
Exit status: 1
声明:本文为原创,作者为 辣条①号,转载时请保留本声明及附带文章链接:https://boke.wsfnk.com/archives/1404.html
谢谢你请我吃辣条谢谢你请我吃辣条

如果文章对你有帮助,欢迎点击上方按钮打赏作者

最后编辑于:2024/9/26作者: 辣条①号

目标:网络规划设计师、系统工程师、ceph存储工程师、云计算工程师。 不负遇见,不谈亏欠!

暂无评论

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

arrow grin ! ? cool roll eek evil razz mrgreen smile oops lol mad twisted wink idea cry shock neutral sad ???

文章目录