【问题标题】:Problems with eval function skipping newlines in $(eval echo $myvar)eval 函数在 $(eval echo $myvar) 中跳过换行的问题
【发布时间】:2013-02-09 13:22:17
【问题描述】:

我目前正在编写一个脚本,旨在为任何基本编辑器添加新的项目生成。 我正在使用以下结构,以便根据用户选择的语言生成正确的基本程序(hello、world):

#!/bin/sh
#this is a short example in the case the user selected C as the language
TXTMAIN="\$TXTMAIN_C"
$TXTMAIN_C="#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
    printf(\"hello, world\n\");
    return EXIT_SUCCESS;
}"
MAIN="./main.c"
touch MAIN
echo -n "$(eval echo $TXTMAIN)" >> "$MAIN"
gedit MAIN

当您编辑 main.c 时,这段代码会给出以下输出:

#include <stdlib.h> #include <stdio.h> int main(int argc, char const* argv[]) { printf("hello, world\n"); return EXIT_SUCCESS; }

但是,当用 echo -n "$TXTMAIN_C" >> "$MAIN" 替换第 13 行时,它会给出正确的输出:

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
    printf("hello, world\n");
    return EXIT_SUCCESS;
}

我仍然不知道这是 echo 还是 eval 问题,或者是否有办法解决我的指针式问题。 非常欢迎任何建议!

【问题讨论】:

  • 单引号是你的朋友。更容易写:TXTMAIN_C='#include ... 因为你不需要转义 " 或 \.

标签: bash pointers eval echo


【解决方案1】:

您的脚本中有一些错误,而且比应有的复杂。

如果您想使用这样的间接变量,请使用${!FOO} 语法,并在适当的地方加上引号:

#!/bin/sh
#this is a short example in the case the user selected C as the language
TXTMAIN=TXTMAIN_C                          # don't force a $ here
TXTMAIN_C="#include <stdlib.h>
#include <stdio.h>
int main(int argc, char const* argv[])
{
    printf(\"hello, world\n\");
    return EXIT_SUCCESS;
}"
MAIN="./main.c"
echo "${!TXTMAIN}" > "$MAIN"                # overwrite here, if you want to 
                                            # append, use >>. `touch` is useless

【讨论】:

  • 嗯,那很快……谢谢,你的回答正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2011-10-05
  • 2011-04-12
  • 1970-01-01
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
相关资源
最近更新 更多