Bash:展开变量(包括复合表达式),而不执行主要命令。

huangapple go评论49阅读模式
英文:

Bash: expand variables (including compound expressions) without executing the main commands

问题

我有一个包含makefile执行输出的文件。其中一些行中有复杂的表达式。例如,其中一行可能包含一些复杂的bash表达式:

gcc main.c -I$(if [ $A == "Val1" ]; then echo /usr/include; else echo /usr/local/include; fi)

该文件可能有数千行。我想知道如何告诉bash:独立评估文件中的每一行的结果,而不实际执行命令。

实际上,$ 只有两种用法:

  • 引用 $A,它是一个始终存在的变量。
  • 嵌套的if,如上所示:$(if ...)
  • $A 的引用可能会发生在 $(if ...) 中,并且有时会在另一个 $(if ...) 中有 $(if ...)
  • 每个 if 中的内容必须在需要调用其他命令的情况下进行评估(据我所知,我认为在这些 if 中调用的唯一命令是对 echo 的调用)。

因此,我希望bash展开并调用解析所有 $ 用法所需的任何命令,但永远不要执行由行代表的命令,而是在标准输出上打印展开的结果。

我该怎么做?

英文:

I have a file that contains the output of a makefile execution. Some of its line have complex expressions in it. For example, one of the lines could include some complex bash expression like:

gcc main.c -I$(if [ $A == "Val1" ]; then echo /usr/include; else echo /usr/local/include; fi)

The file could have thousand of lines. I want to know how could I tell bash: echo the result of evaluating each one of line of this file independently, without actually executing the commands.

Actually, there's only one two usages of $:

  • To refer to $A, which is a variable that always exists.
  • An embedded if as shown above: $(if ...)
  • References to $A can happen inside $(if ...)s, and sometimes there's an $(if ...) inside another $(if ...).
  • The contents within each if must be evaluated in case there's calls to other commands (as far as I've found, the only command that I think is called inside such ifs are calls to echo).

So I want bash to expand and call whatever command is required to resolve all $ usages, but never execute the command represented by the line itself, but print the expanded result on the standard output instead.

How can I do that?

答案1

得分: 2

将整个文件放入一个未引用的heredoc中。即:

#!/usr/bin/env bash
: "${A?错误:在运行此代码之前,变量A必须始终存在}"
cat <<EOF
# ...将整个文件的内容放在这里...
# ...包括这一行...
gcc main.c -I$(if [ $A == "Val1" ]; then echo /usr/include; else echo /usr/local/include; fi)
EOF

内容将进行扩展,但不会被执行。

英文:

Put your an entire file in an unquoted heredoc. That is:

#!/usr/bin/env bash
: &quot;${A?Error: variable A must always exist before running this code}&quot;
cat &lt;&lt;EOF
# ...put your entire file&#39;s contents here...
# ...including the line...
gcc main.c -I$(if [ $A == &quot;Val1&quot; ]; then echo /usr/include; else echo /usr/local/include; fi)
EOF

The contents will have expansions performed, but not otherwise be executed.

huangapple
  • 本文由 发表于 2023年6月8日 20:45:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76431992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定