echo 命令的神秘行为

Roh*_*yen 2 command-line bash scripts echo

当我们需要在echo命令中使用转义序列字符时,我们必须使用该-e选项。喜欢

echo -e "Enter your name : \c"
Run Code Online (Sandbox Code Playgroud)

但是当我们在 shell 程序(.sh 文件)中包含这种语句时,它会产生一个神秘的错误。它打印

-e Enter your name : 
Run Code Online (Sandbox Code Playgroud)

它不需要-e带有 echo 命令的选项,就像我们这样写一样

echo "Enter your name : \c"
Run Code Online (Sandbox Code Playgroud)

它显示没有错误的输出,但这在 shell 中不起作用。

那是什么原因呢?我正在使用 bash shell 和 Ubuntu 15.04 版本。

mur*_*uru 7

我猜您没有使用过shebang(#! /bin/bash作为脚本的第一行)。在这种情况下,脚本使用 运行/bin/sh,即/bin/dash. 并且echoindash不支持非标准-e(查看POSIX 标准)。你真的不应该使用echo -e. printf改为使用更便携的行为。请参阅为什么printf比 echo 更好?在 Unix 和 Linux 上。以下命令的行为应该相同:

bash -c 'printf "%s" "Enter your name"'
dash -c 'printf "%s" "Enter your name"'
Run Code Online (Sandbox Code Playgroud)

  • +1。`echo` 是出了名的不便携。 (3认同)