Apple - Why `echo -n` doesn't work in this script on mac terminal?
Echo is both a binary program (/bin/echo
) as well as builtin command in some shells such as bash and sh. As man echo
states,
Some shells may provide a builtin echo command which is similar or iden- tical to this utility. Most notably, the builtin echo in sh(1) does not accept the -n option. Consult the builtin(1) manual page.
In order to fix this, you can change your script to use bash by setting the first line to
#!/bin/bash
Or change your invocation of echo to
/bin/echo -n "$b "
echo
is not portable as you experienced. I would suggest to use the POSIX alternative printf
:
printf "$b "
Note that in the general case, if you don't know in advance what contains $b
, you should use instead:
printf "%s " "$b"
Appending '\c' as per "man echo" documentation seemed to do this for me. So ... on line 9 the change would like below
#!/bin/sh
a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo "$b \c"
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done