如何像直接傳遞字串一樣取得格式化文字?

如何像直接傳遞字串一樣取得格式化文字?

$直接用to傳遞字串echo

$ echo $'#include <iostream>\nint main() {\n  std::cout << \"Hello World!\" << std::endl;\n}'

擴展了嵌入的 ANSI 轉義序列

#include <iostream>
int main() {
  std::cout << "Hello World!" << std::endl;
}

我將字串分配給一個變數

codeStr='#include <iostream>\nint main() {\n  std::cout << \"Hello World!\" << std::endl;\n}'

然後回顯變數

echo $codeStr

我得到的是原始字串而不是格式化文字。

如何像直接傳遞字串一樣取得格式化文字?

答案1

使用-e切換到enable interpretation of backslash escapes

$ codeStr='#include <iostream>\nint main() {\n  std::cout << \"Hello World!\" << std::endl;\n}'
$ echo -e $codeStr 
#include <iostream>
int main() {
 std::cout << \"Hello World!\" << std::endl;
}

解決 @steeldriver 註釋printf也有效(並且它正確解釋了序列)。

$ codeStr='#include <iostream>\nint main() {\n  std::cout << \"Hello World!\" << std::endl;\n}'
$ printf "$codeStr"
#include <iostream>
int main() {
  std::cout << "Hello World!" << std::endl;
}

相關內容