问题
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.
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 Row 1
-n 1
-n 2
... And so on
回答1:
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, 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.
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 "
回答2:
I just tested your code on my system, and it seems to work correctly in bash. However, I do get the exact error that you described when I run it in straight sh. Assuming that you are running this on a Mac, try running /bin/bash
before running your script.
Assuming that your script is in a file, you can also add #!/bin/bash
as the first line of your script (this tells the computer to execute it with bash).
来源:https://stackoverflow.com/questions/35712644/echo-n-with-string-argument-printing-the-n-part-even-though-not-within-quot