2023-06-23 10:00:00

"echo -n"打印"-n"

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

echo -n "Some string..."

打印

-n Some string...

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

Some string...

当前回答

Bash有一个“内置”命令叫做“echo”:

$ type echo
echo is a shell builtin

此外,还有一个“echo”命令,它是一个适当的可执行文件(也就是说,shell fork和execs /bin/echo,而不是解释echo并执行它):

$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21  2011 /bin/echo

两个echo对于\c和-n的行为是不同的。最好的办法是使用printf,它可以在四种不同的*NIX版本上使用:

$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"

其他回答

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

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

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

Bash有一个“内置”命令叫做“echo”:

$ type echo
echo is a shell builtin

此外,还有一个“echo”命令,它是一个适当的可执行文件(也就是说,shell fork和execs /bin/echo,而不是解释echo并执行它):

$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21  2011 /bin/echo

两个echo对于\c和-n的行为是不同的。最好的办法是使用printf,它可以在四种不同的*NIX版本上使用:

$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"

我在IBM z/OS中遇到了同样的问题,所以我使用了print而不是echo,而且它有效。

print -n "Some string ...."

print -从shell返回参数

试着用

echo -e "Some string...\c"

正如我从你的问题中理解的那样,它对我来说是有效的。

请注意,我从手册页获得了这些信息。手册页还指出shell可能有自己的echo版本,我不确定bash是否有自己的版本。