文章目录
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
如果文章对你有帮助,欢迎点击上方按钮打赏作者
暂无评论