gpt4 book ai didi

linux - 在 bash 脚本中使用标志

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:22 25 4
gpt4 key购买 nike

Linux 中的脚本以一些声明开始,例如:

#!/bin/bash

如果我错了请纠正我:这可能说明了要使用哪个 shell。

我也看到一些脚本说:

#!/bin/bash -ex

标志 -ex 的用途是什么

最佳答案

#!/bin/bash -ex

<=>

#!/bin/bash
set -e -x

手册页(http://ss64.com/bash/set.html):

-e  Exit immediately if a simple command exits with a non-zero status, unless
the command that fails is part of an until or while loop, part of an
if statement, part of a && or || list, or if the command's return status
is being inverted using !. -o errexit

-x Print a trace of simple commands and their arguments
after they are expanded and before they are executed. -o xtrace

更新:

顺便说一句,可以在不修改脚本的情况下设置开关。

例如我们有脚本t.sh:

#!/bin/bash

echo "before false"
false
echo "after false"

并想跟踪这个脚本:bash -x t.sh

输出:

 + echo 'before false'
before false
+ false
+ echo 'after false'
after false

例如,我们想跟踪脚本并在某些命令失败时停止(在我们的例子中它将通过命令 false 完成):bash -ex t.sh

输出:

+ echo 'before false'
before false
+ false

关于linux - 在 bash 脚本中使用标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39672509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com