英文:
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 suchif
s are calls toecho
).
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
: "${A?Error: variable A must always exist before running this code}"
cat <<EOF
# ...put your entire file's contents here...
# ...including the line...
gcc main.c -I$(if [ $A == "Val1" ]; then echo /usr/include; else echo /usr/local/include; fi)
EOF
The contents will have expansions performed, but not otherwise be executed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论