Re: problems with loop in bash
- From: Jon LaBadie <jlabadie@xxxxxxxxx>
- Date: Tue, 13 Apr 2010 18:03:37 -0400
Regarding echo vs. printf,
Printf has another advantage over echo: it recognizes many special escape sequences that echo does not recognize (or recognizes only with -e in certain implementations), like \n or \t.
Houghi, pk and I represent different sides of the problem. I've worked most
of my UNIX life in environments where echo DID recognize \n, \t, etc. So I
expect other behaviors, such as pk considers normal, as abberant.
I'd re-write pk's statement to say that as printf is consistant in recognizing
the escape sequences like \n, \t, etc. while echo is not.
If you are going to do simple literal text that does not contain escape
sequences, go ahead and use echo. For example:
echo "Hello World!"
But is that easier than:
printf "Hello World!\n"
Well I guess it is harder because you have to add the '\n' in printf. But
that is balanced by times you don't want a newline. For example suppose you
want to ask for some data to be keyed in by the operator. Further, suppose
you want the data entry on the same line as the prompt. With printf
you might do this:
printf "Enter your last name: "
But with echo you would have to remember, does my echo suppress the default
newline by putting a '\c' at the end or by using a '-n' option? I.e. should
echo "Enter your last name: \c" OR echo -n "Enter your last name: "
And what about when I copy my script to my laptop, or my next new computer.
Will its echo work the same way as this version?
I realize you are not "smart enough" to learn the intricacies of printf :)
but I find the ability to format multiple lines of simple text a great
feature. For example, suppose you are printing a list of names, first and
last. You could use a printf like this:
printf "%s %s\n" "$FirstName" "$LastName"
with output like (which is no different than you could get with echo):
But changing each %s to %12s would change the output to:
Ahh, maybe you wanted left instead of right alignment, make it %-12s:
Or the first one %12s and the second one %-12s
Lots and lots of flexibility that would be difficult to do with echo.
Yet the simple things are still simple (and more portable) with printf.
- Prev by Date: Re: problems with loop in bash
- Next by Date: Re: problems with loop in bash
- Previous by thread: Re: problems with loop in bash
- Next by thread: Re: problems with loop in bash