[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Prompting \n



T o n g wrote:
> What I didn't make clear in the OP was that, I was actually looking for a 
> general purpose command that can show whatever messages thrown to it, 
> including the common backslash escapes. echo -e does a good job, but 

But 'echo -e' isn't portable.

> printf will choke on any of its control characters, e.g., %.

In that case use %b and print everything as a string like echo.

  $ printf "%b" "Hello world!"

  $ printf "%b" "Hello %1 %2 %3"
  Hello %1 %2 %3

  $ printf "%b" "Hello1 %1\nHello2 %2\nHello3 %3"
  Hello1 %1
  Hello2 %2
  Hello3 %3

> Today, I just found that printf cannot be used to show whatever the 
> command line is.

Yes it can.

> Here is an example:
> 
>   set -- command -opt param params...
> 
>   echo='echo -e'
> 
>   $ $echo "\n> $@\n"
> 
>   > command -opt param params...

That is quite a convoluted example.

> So far so good. Now try printf:
> 
>   $ printf "\n> $@\n"
> 
>   > command
> 
> What's happening? why printf chokes on '-'?

Because $@ is quoted it is being split up into separate arguments.  If
you want to use all of the arguments together in a string you need to
use $* not $@.  This works as you expect.

  $ printf "\n> $*\n"

You can see what "$@" does by using it with a for loop and printing
each argument in turn.

 $ for i in "\n> $@\n"; do echo _"$i"_;done
  _\n> command_
  _-opt_
  _param_
  _params...\n_

  $ for i in "\n> $*\n"; do echo _"$i"_;done
  _\n> command -opt param params...\n_

Use "$@" when you want each argument in separate strings.  Use "$*"
when you want all of the arguments together in one string.

> BTW, the reason that I gave up 'echo -e' was that it started to 
> mysteriously output that "-e " in front of the messages I wanted to show 
> in my /bin/sh scripts. I still haven't figure out why yet. 

You were probably calling it twice with echo -e -e.

Bob

Attachment: signature.asc
Description: Digital signature


Reply to: