Bash:执行前高亮显示命令(设置-x) [英] Bash: highlight command before execution (set -x)

查看:71
本文介绍了Bash:执行前高亮显示命令(设置-x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个执行约20条命令的bash脚本,出于调试目的,我发现自己在输出中滚动了很多.不幸的是,bash不能告诉我输出的哪一部分是什么命令的一部分.当我在脚本中使用"set -x"时,它至少会打印一些有关其执行内容的信息,但我并不真正喜欢它生成的输出.

I have a bash script which executes about 20 commands and for debugging purposes I find myself scrolling through the output a lot. Unfortunately bash doesn't tell me which part of the output is part of what command. When I use "set -x" in the script it at least prints some information on what it just executed, but I don't really like the output it generates.

例如,如果我有此脚本:

For instance, if I have this script:

#!/bin/bash

set -x
echo "foo"
if [ "$ASD" == "QWE" ] ; then
    echo "bar"
fi

我希望输出是这样的:

回显"foo"
foo
回显栏"
酒吧

或者:

回显"foo"
foo
if [" value_of_ASD"==" QWE];然后
回显栏"
酒吧
fi

与其以粗体显示命令,还可以用颜色突出显示.但是我不只是想在命令前面加上"+"字符,而且我也不希望if语句显示为'['value_of_ASD == QWE']'.

Instead of printing the commands in bold, highlighting with a color would also be okay. But I don't just want to have "+" characters in front of the commands and I also don't like the if statements showing up like '[' value_of_ASD == QWE ']'.

我如何用bash做到这一点?

How can I accomplish that with bash?

此刻输出如下所示:

+ echo foo
foo
+ '[' value_of_ASD == QWE ']'
+ echo bar
bar

我的一个想法是编写一个脚本,该脚本将在主脚本的开始处提供,然后让源脚本解析主脚本.像这样:

One idea I had was to write a script that I would source in the very beginning of the main script and then let the sourced script parse the main one. Something like this:

source_me.sh

#!/bin/bash
SCRIPT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/$(basename $0)"
FORMAT_SET_BOLD='\033[0;1m'
FORMAT_RESET='\033[0m'

cat $SCRIPT_PATH | tail -n "+$START_LINE" | while read line; do
    printf "${FORMAT_SET_BOLD}${line}${FORMAT_RESET}\n"
    eval "${line}"
done

exit 0;

main.sh

#!/bin/bash
START_LINE=$((LINENO+1)) source ./source_me.sh

echo "Foo"
echo "Bar"
echo "+Hello"

在这种情况下的输出是:

The output in that case is:

回显"Foo"

回声酒吧"
酒吧
回声"+你好"
+你好

但是,如果我使用遍及多行的更复杂的代码(例如语句,循环等),则此方法将失败:

But this method will fail if I use more complex code that goes over multiple lines (if statements, loops etc):

#!/bin/bash
START_LINE=$((LINENO+1)) source ./source_me.sh

echo "Foo"

if [ "$FOOBAR" == "" ] ; then
    echo "Bar"
fi

echo "+Hello"

在这种情况下,我得到:

In this case I get:

回显"Foo"

if ["$ FOOBAR" =="];然后
./source_me.sh:eval:第9行:语法错误:文件意外结束
回显酒吧"
酒吧
fi
./source_me.sh:eval:第8行:意外标记"fi"附近的语法错误
./source_me.sh:评估:第8行:"fi"

if [ "$FOOBAR" == "" ] ; then
./source_me.sh: eval: line 9: syntax error: unexpected end of file
echo "Bar"
Bar
fi
./source_me.sh: eval: line 8: syntax error near unexpected token ´fi'
./source_me.sh: eval: line 8: ´fi'

回显"+你好"
+你好

推荐答案

您可以通过设置 PS4 + 更改为所需的字符串,例如:

You can change the + to a string of your desire by setting PS4, e.g.:

PS4="# "; set -x

这篇关于Bash:执行前高亮显示命令(设置-x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆