在 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 a
和wc -c
在为命令替换创建的子 shell 中执行,因此它们得到两个 +
,而n=<result>
在原始 shell 中使用单个 +
执行.
关于bash - 当 "set -x"时,Bash 中 stderr 中 + 号的数量是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73829702/