"echo" sh 和 bash 输出不同的答案

"echo" output different answer by sh and bash

我 运行 我的脚本使用了三种方式,但输出不同,你能向我解释一下为什么会这样吗?谢谢!! 这是我的脚本

#!/bin/bash
#Program:
#     This program shows "Hello World!" in your screen.
echo -e "Hello World! \a\n" 
exit 0

如果我 运行 它由 bash 和 ./ like bash sh01.sh 输出是

Hello World!

但是,如果我像 sh sh01.sh 这样使用 sh,它会像

-e Hello World!

还有一些其他信息

  1. OS: Ubuntu 16.04.3
  2. 键入 sh -> 破折号

echo 不是很便携(甚至 Bash 的 echo 在不同的操作系统上可能表现不同,编译 Bash 时可能使用不同的默认选项)。您可以使用 printf。根据posix:

It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted. The printf utility can be used portably to emulate any of the traditional behaviors of the echo utility [...]