Bash 脚本不在回显子进程中回显新行

Bash script not echoing new lines in echo subprocess

当我在我的终端上 运行 这个脚本时,它与换行符完美配合

echo -e $(echo "a \na")

输出:

a 
a

当我将其封装在 bash 脚本中时 - test.sh:

#!/bin/sh

echo -e $(echo "a \na")

然后我调用 ./test.sh,我得到这个输出:

-e a a

如何让 bash 脚本直接在终端上提供与 运行ning 相同的换行输出?

使用printfecho 不可移植。有些 shell 不知道 -e 之类的。此外,使用 printf 您将获得更多格式选项。

printf "%s\n%s\n" a a
#or
printf "a\na\n"

您问题的答案在@that other guy's评论中:

Make the shebang #!/bin/bash, otherwise it's a sh script and not a bash script

例如

sh test.sh
# -e a a
bash test.sh
# a
# a
dash test.sh
# -e a a
zsh test.sh
# a a

所以...使用 printf - 将在任何地方工作并给出相同的结果。