bash 和 sh 的输出不同吗?

Man*_*rti 3 bash scripts

我有代码来打印给定数字的简单乘法表。当我用 sh 运行它时,它给了我完美的输出,但是当我使用 bash 时,它给出了略有不同的输出。你能解释一下这是为什么吗?

这是输出 sh

sh cd.sh 

enter the no to print table
12

12 * 1 =12
12 * 2 =24
12 * 3 =36
12 * 4 =48
12 * 5 =60
12 * 6 =72
12 * 7 =84
12 * 8 =96
12 * 9 =108
12 * 10 =120

COntinue.. or not [0/1] 
1

exiting the script
Run Code Online (Sandbox Code Playgroud)

bash

bash cd.sh 

enter the no to print table
12

\t12 * 1 =12
\t12 * 2 =24
\t12 * 3 =36
\t12 * 4 =48
\t12 * 5 =60
\t12 * 6 =72
\t12 * 7 =84
\t12 * 8 =96
\t12 * 9 =108
\t12 * 10 =120

COntinue.. or not [0/1] 
1

exiting the script
Run Code Online (Sandbox Code Playgroud)

这是我的代码。我已经更正了每个错误,所以如果您遇到任何错误,请忽略任何错误!只关注输出中的“\t”

hee*_*ayl 6

原因是默认情况下bash的内置echo(以及外部/bin/echo)不理解反斜杠转义(\),因此按\t字面意思处理(而不是制表符)。

您需要使用-e带有bash's builtin的选项echo

来自help echo

-e     enable interpretation of backslash escapes
Run Code Online (Sandbox Code Playgroud)

所以在bash(或使用/bin/echo)你需要:

echo -e "\t$num * $i =$s"
Run Code Online (Sandbox Code Playgroud)

另一方面,sh's ( dash) 内置echo默认解释\t为制表符,因此在sh.


要使其在所有符合 POSIX 的 shell 中可移植,请使用printf

printf '\t%s * %s =%s\n' "$num" "$i" "$s"
Run Code Online (Sandbox Code Playgroud)