My new 564-page book, Shell Scripting, published by Wiley, is on sale now. Please click "Like" on the left if you are on Facebook, or just click here to get the book.

Echo : -n vs \c

As you may have noticed by now, when you use the echo statement, a newline is added at the end of the command. There is a fix for this ... well, more accurately, there are two fixes for this.

Some Unix systems use echo -n message to tell echo not to append a newline; others use echo message \c to do the same thing:
echo -n "Enter your name: "
read name
echo "Hello, $name"
This will work on some systems, and will look like this:
Enter your name: Steve
Hello, Steve
However, on other systems, you need to write the code like this:
echo "Enter your name: \c"
read name
echo "Hello, $name"
Which will provide the same results for those systems.

Well, that's a pain. Here's a workaround which will work on both:

         if [ "`echo -n`" = "-n" ]; then
	  	n=""
	  	c="\c"
         else
	  	n="-n"
	  	c=""
         fi

  echo $n Enter your name: $c
  read name
  echo "Hello, $name"
If echo -n wasn't interpreted properly, it would just echo out the text -n, in which case, $n is set to the empty string, and $c is set to \c. Otherwise, the opposite is done, so $n is set to -n, and $c is set to the empty string.
My new 564-page book, Shell Scripting, published by Wiley, is on sale now. Please click "Like" on the left if you are on Facebook, or just click here to get the book.
Steve's Bourne / Bash shell scripting tutorial
Share on Twitter Share on Facebook Share on LinkedIn Share on Identi.ca Share on StumbleUpon

Want to take the tutorial with you?

My Shell Scripting Book:
    Shell Scripting, Expert Recipes for Linux, Bash and more
is available online and from all good booksellers.

Buy my 600-page Shell Scripting Book...

From Amazon USA:

From Amazon UK:

For Kindle:

Or From other retailers

You can also find the book, and join a shell scripting community, on Facebook:


Option Two: Buy the 70-page PDF (£4.99/$9.99/€6.99)
(Free Sample)

And you can always Download my Free Shell Scripting Cheatsheet PDF