2023-06-23 10:00:00

"echo -n"打印"-n"

我在我的脚本中有一个echo的问题:

echo -n "Some string..."

打印

-n Some string...

然后转到下一行。在控制台中,没有换行符,它可以正常工作:

Some string...

当前回答

enable -n echo
echo -n "Some string..."

其他回答

仅就最流行的Linux发行版Ubuntu及其Bash而言:

检查您正在使用哪个shell。主要是以下作品,其他看这个: echo $ 0 如果上面打印bash,那么下面将工作: Printf "hello with no new line print in end" 或 Echo -n "hello with no new line in end"

为了达到这个目的,我经常使用两种方法:

1. 使用光标转义字符(\c)和echo -e

例子:

for i in {0..10..2}; do
  echo -e "$i \c"              
done
# 0 2 4 6 8 10

-e flag启用字符串中的转义字符。 \c将光标返回到当前行。

OR

2. 使用printf命令

例子:

for ((i = 0; i < 5; ++i)); do
  printf "$i "
done
# 0 1 2 3 4

echo命令有多个版本,具有不同的行为。显然,用于脚本的shell使用了一个不识别-n的版本。

printf命令具有更一致的行为。echo适用于简单的echo hello,但我建议使用printf处理更复杂的事情。

您在什么系统上,您的脚本使用什么shell ?

注意,AIX上的/usr/bin/echo和/bin/echo不支持任何参数,因此如果使用sh或KornShell (ksh) shell, -n和-e都不起作用。

C shell和Bash有自己的内置echo,支持-n。 这是相关的,因为许多shell脚本显式地使用sh或KornShell。

AIX确实有/usr/bin/printf,因此正如前面的一些回答中所建议的,

$ printf "whatever"

相当于echo -n "whatever",其中支持-n。

当您开始编写shell脚本时,请始终使用#!/usr/bin/env bash作为第一行。

该shell不会省略或操作转义序列。

例子:

echo "This is first \\n line"

打印

This is first \n line.