samedi 21 février 2015

Why `echo -n` doesn't work in this script on mac terminal?


I am learning shell from tutorialspoint today:http://ift.tt/1FFbBej


And I copied this code block to a loop.sh file:



#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done


But when excute it, I got things like:



...
-n 4
-n 3
-n 2
-n 1
-n 0
...


Apparently, the -n flag doesn't work in echo -n "$b ".


Then I move the same file to my Ubuntu virtual system. Runs it.


I got :



0
1 0
2 1 0
3 2 1 0
4 3 2 1 0
5 4 3 2 1 0
6 5 4 3 2 1 0
7 6 5 4 3 2 1 0
8 7 6 5 4 3 2 1 0
9 8 7 6 5 4 3 2 1 0


I'm confused, though Ubuntu use dash as its default sh, but OSX use official bourne shell as its sh, why the script failed here? How to fix it?





1 commentaire: