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

Re: "echo" literally in sh scripts (was: why would "tr --complement --squeeze-repeats ..." append the substitution char once more? ...)



On Mon, Dec 11, 2023 at 10:16:35AM -0500, Stefan Monnier wrote:
> > 1) Many implementations of echo will interpret parts of their argument(s),
> >    in addition to processing options like -n.  If you want to print a
> >    variable's contents to standard output without *any* interpretation,
> >    use printf.
> >
> >     printf %s "$myvar"
> >     printf '%s\n' "$myvar"
> 
> Interesting.  I used the following instead:
> 
>     bugit_echo () {
>         # POSIX `echo` has all kinds of "features" we don't want, such as
>         # handling of \c and -n.
>         cat <<ENDDOC
>     $*
>     ENDDOC
>     }

That requires an external command (one fork), plus whatever overhead is
used by the << implementation (temp file or pipe, depending on shell and
version).  It's not wrong, but an implementation using nothing but
builtins is usually preferable.

    echo() { printf '%s\n' "$*"; }

It's also worth mentioning that both of these rely on the expansion of $*
with a default or nearly-default IFS variable.  If you want it to work
when IFS may have been altered, you can do this in bash:

    echo() { local IFS=' '; printf '%s\n' "$*"; }

In sh, you'd need to fork a subshell:

    echo() { (IFS=' '; printf '%s\n' "$*"); }

Or if you're a golfer:

    echo() (IFS=' '; printf '%s\n' "$*")

I *really* dislike that syntax, but that's just me.  Some people use it.


Reply to: