问题描述
我一直在学习如何在bash中编写脚本,但遇到一个令人沮丧的错误.在下面的代码中,该代码只运行10行,每行十行,每十行打印一次,每当 echo -n"$ j"
运行时,输出将同时输出新行和"-n" echo
命令的参数.
I've been learning how to script in bash, but I'm coming across a frustrating bug. In the below code, which just runs to print 10 rows and ten with ten columns, whenever the echo -n "$j "
runs, the output prints out both a new line and the "-n" argument to the echo
command.
echo命令和echo -n都可以很好地工作,但是由于某些原因,请不要在此脚本中使用...预先致谢
The echo command and the echo -n both work perfectly fine on their own, but for some reason, don't work within this script... Thank you in advance
#Nested for loop
for i in 1 2 3 4 5 6 7 8 9 10
do
echo -n "Row $i: "
for j in 1 2 3 4 5 6 7 8 9 10
do
sleep 1
echo -n "$j "
done
echo #Outputs new line
done
输出看起来像这样...
Output looks like this...
-n第1行
-n 1
-n 2
...等等
推荐答案
echo
的某些实现将 -n
解释为不要在末尾添加换行符"",但其他人只是将其视为要打印的字符串的一部分.同一实现的不同版本之间甚至可能有所不同!根据 echo
的单Unix规范描述,除非省略 -n
(作为第一个参数)和转义序列,否则不可能在所有POSIX系统上都可移植地使用echo."
Some implementations of echo
interpret -n
as meaning "don't add a linefeed at the end", but others just treat it as part of the string to print. It can even be different between different versions of the same implementation! According to the Single Unix Specification description of echo
, "It is not possible to use echo portably across all POSIX systems unless both -n
(as the first argument) and escape sequences are omitted."
IIRC(一个OS X版本(可能是10.5.0?)附带的bash版本)将 -n
视为要打印的字符串的一部分,所以我的一堆脚本坏了.
IIRC, the version of bash that shipped with one version of OS X (10.5.0 maybe?) treated -n
as part of the string to print, and a bunch of my scripts broke.
所以我学会了改用 printf
.它比 echo
稍微复杂一些,但是却更具可移植性和可预测性.棘手的是,第一个参数是一个格式字符串,说明如何打印其余参数.要替换标准的 echo"somestring"
命令,可以使用 printf%s \ n""somestring"
.对于 echo -n"somestring"
,只需将 \ n
保留为以下格式字符串: printf%s""somestring"
.因此,在您的情况下:
So I learned to use printf
instead. It's slightly more complicated than echo
, but far more portable and predictable. The tricky thing is that the first argument is a format string that says how to print the rest of the arguments. To replace a standard echo "somestring"
command, you'd use printf "%s\n" "somestring"
. For echo -n "somestring"
, just leave the \n
out of the format string: printf "%s" "somestring"
. So in your case:
printf "%s" "$j "
这篇关于Echo -n使用String参数打印"-n"部分,即使不在引号内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!