Answers:
该echo命令有多个版本,具有不同的行为。显然,用于脚本的Shell使用的版本无法识别-n。
该printf命令具有更一致的行为。echo对于诸如之类的简单事情也可以echo hello,但我建议printf对更复杂的事情使用。
您在什么系统上,脚本使用什么外壳?
#!/bin/bash它就起作用了。通常我正在使用bash。
printf命令。
echo总是添加换行符...解决方法充其量是充其量。
%是您的shell提示符。试试看,并仔细观察:printf hello; sleep 5
bash 有一个名为“ echo”的“内置”命令:
$ type echo
echo is a shell builtin
另外,还有一个“ echo”命令,该命令是适当的可执行文件(即,与/bin/echo解释echo和执行命令相反,它们是shell forks和execs ):
$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21 2011 /bin/echo
无论是行为echo的WRT来\c和-n变化。最好的选择是使用printf,我可以在四种不同的* NIX风格中使用它:
$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"
试试看
echo -e "Some string...\c"
正如我从您的问题中了解到的那样,它对我有效。
请注意,我是从man页面上获得此信息的。该man页面还指出,shell可能具有其自己的版本echo,并且不确定是否bash具有其自己的版本。
echo "some string...\c"。但是,如果您需要使用截然不同的echo命令来支持多个bash变体,则可能最好使用printf,或者需要使用类似的东西检查echo命令的功能[ -n "$( echo -e )" ] && echo "sh stuff\c" || echo -e "bash stuff\c"(至少bash也支持\ c,因此无需使用-n选项,但需要-e进行bash)
仅适用于最受欢迎的linux Ubuntu,它是bash:
检查您使用的是哪个外壳?大多在下面的作品,否则看到这个:
echo $0
如果上面打印了bash,则下面的内容可以工作:
printf "hello with no new line printed at end"
要么
echo -n "hello with no new line printed at end"
在编写脚本时,shell脚本始终将第一行作为#!/ usr / bin / env bash。此shell不会忽略或操纵转义序列。ex echo“这是第一\ n行”打印这是第一\ n行。
enable -n echo
echo -n "Some string..."
bash以bourne shell模式运行,则在这里工作正常。而且,您不太可能真正使用bourne shell作为交互式shell,不是吗?