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

  • 本文关键字:是什么 符号 stderr set Bash bash
  • 更新时间 :
  • 英文 :


在Bash中,您可以看到

set --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

并且在脚本中运行的顶级命令将具有单个CCD_ 8。

例如命令

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

产生输出

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

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

来自man bash:

-x
展开每个简单命令后,对于命令、大小写命令、选择命令或命令的算术,显示PS4的展开值,然后是命令及其展开参数或相关单词列表。

那么这里的PS4是什么?

PS4
此参数的值与PS1一样展开,并且在执行跟踪期间显示每个命令bash之前打印该值。根据需要,PS4的扩展值的第一个字符被多次复制,以指示多个间接级别。默认值为+

";间接;据我所知,没有进一步解释。。。

最新更新