bash执行时打印bash脚本注释

问题描述 投票:0回答:4

假设我有一个 bash 脚本

test.sh
:

#!/bin/bash

# Comment 1
echo "Hello world"

# Comment 2
echo "Hi there"

我知道在使 bash 脚本可执行并运行它之后,只有

echo
命令会显示为输出。

我想知道是否有办法打印执行时的注释。也就是说,我希望输出看起来像:

Comment 1
Hello world

Comment 2
Hi there
bash shell sh
4个回答
0
投票

是否有办法打印执行时的注释

不行,没有办法。

一条路

修改 bash 源代码并修改语言解析器以解析

#
字符以用作
; echo

在不需要真正崩溃的解析器的简单情况下,您可以将源文件中的所有

#
替换为
echo
然后运行它。喜欢
sed 's/#/echo/' test.sh | bash -s


0
投票

就像

user1934428
所说的

不完全是你想要的,但如果你将 shebang 设置为

#!/bin/sh -x
(或
-v
),它将打印出两者脚本中的注释和命令

其他参考:https://stackoverflow.com/a/2853811/10359765


0
投票

一种常见的安排是设置各种日志记录级别,然后根据日志记录级别发出不同数量的日志记录。

debug () { ${debug-:} "$0: $@" >&2; }
info () {  ${info-:}  "$0: $@" >&2; }
warn () {  ${warn-:}  "$0: $@" >&2; }
error () { ${error-:} "$0: $@" >&2; }

case $1 in
  --debug) debug=echo; info=echo;  warn=echo;  error=1;;
  --info)  info=echo;  warn=echo;  error=1;;
  --warn)  warn=echo;  error=echo;;
  --error) error=echo;;
  -*) echo "$0: unknown option '$1' -- aborting" >&2
      exit 127;;
esac
shift

debug here we go
info starting
echo "Hello world"
warn the end is nigh
echo "Hi there"
error we die here

这只是一个非常简单的演示;如果没有明确指定级别,您可能希望它更加安全和通用,并且具有合理的默认值,例如使用

--warn
运行(这意味着
--error
)。

在此实现中,“注释”不再是注释,输出将转到标准错误;但正如您所看到的,这还可以让您添加“注释”,这些注释在您调试时实际上很有用,而不仅仅是在阅读代码时。

您可以通过重命名命令(

debug
warn
等)使其看起来更像注释,也许重命名为
_dbg_
_warn_
等。


0
投票

看起来是一个很晚的答案,但也许有人会需要它!

试试这个:

#!/bin/bash

回声-- echo - 任何评论 - 回声--

ls -la # 或任何命令!

© www.soinside.com 2019 - 2024. All rights reserved.