bash - 当 "set -x"时,Bash 中 stderr 中 + 号的数量是什么意思

标签 bash

在 Bash 中,你可以看到

设置 --help

  -x  Print commands and their arguments as they are executed.

测试代码如下:

# make script
echo '
    #!/bin/bash
    set -x
    n=$(echo "a" | wc -c)
    for i in $(seq $n)
    do
        file=test_$i.txt
        eval "ls -l | head -$i"> $file
        rm $file
    done
' > test.sh
# execute
chmod +x test.sh
./test.sh 2> stderr
# check
cat stderr

输出

+++ echo a
+++ wc -c
++ n=2
+++ seq 2
++ for i in $(seq $n)
++ file=test_1.txt
++ eval 'ls -l | head -1'
+++ ls -l
+++ head -1
++ rm test_1.txt
++ for i in $(seq $n)
++ file=test_2.txt
++ eval 'ls -l | head -2'
+++ ls -l
+++ head -2
++ rm test_2.txt

文件中每行开头的 + 符号的数量有何含义?这很明显,但我想避免误解。
另外,那里可以出现一个+符号吗?如果是的话,它的含义是什么?

最佳答案

数量+代表子shell嵌套深度。

请注意整个test.sh脚本正在子 shell 中运行,因为它不以 #!/bin/bash 开头。它必须位于脚本的第一行,但它位于第二行,因为 echo 的开头有一个换行符包含脚本的参数。

当脚本以这种方式运行时,它由原始 shell 在子 shell 中执行,大约类似于

( source test.sh )

将其更改为

echo '#!/bin/bash
    set -x
    n=$(echo "a" | wc -c)
    for i in $(seq $n)
    do
        file=test_$i.txt
        eval "ls -l | head -$i"> $file
        rm $file
    done
' > test.sh

并且在脚本中运行的顶级命令将有一个 + .

例如命令

n=$(echo "a" | wc -c)

产生输出

++ echo a
++ wc -c
+ n='       2'

echo awc -c在为命令替换创建的子 shell 中执行,因此它们得到两个 + ,而n=<result>在原始 shell 中使用单个 + 执行.

关于bash - 当 "set -x"时,Bash 中 stderr 中 + 号的数量是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73829702/

相关文章:

bash - 将文件的每一行分配为一个变量

regex - shell脚本中的动态字符串搜索

linux - Bash 脚本 - 浮点异常

linux - 如何从 bash 中的第二个文件 sh 中读取值?

linux - 使用 shell 解析字符串

linux - 我如何使用正则表达式获取文件的特定字符串

string - 在 bash 中使用随机可打印字符串创建特定大小的文件

bash - Grep 匹配的行包括下面和另一个匹配的行包括上面

bash - 如果参数超过 9 个,如何访问函数的参数?

bash - 我应该查看什么 snmp OID 以查看我的打印机和交换机是否正在运行