echoing arbitrary text in bash?

echoing arbitrary text in bash?

am 09.04.2008 06:42:57 von Mark Reed

in bash, echo "$x" fails if $x is e.g. "-n". ksh has the - option to
print to handle this case, but bash echo doesn't seem to. So how can
I reliably output a variable whose contents are unknown?

Re: echoing arbitrary text in bash?

am 09.04.2008 06:46:59 von Ed Morton

On 4/8/2008 11:42 PM, Mark Reed wrote:
> in bash, echo "$x" fails if $x is e.g. "-n". ksh has the - option to
> print to handle this case, but bash echo doesn't seem to. So how can
> I reliably output a variable whose contents are unknown?
>

printf "%s\n" "$x"

Re: echoing arbitrary text in bash?

am 09.04.2008 09:35:40 von andrej.panjkov

On Apr 9, 2:42 pm, Mark Reed wrote:
> in bash, echo "$x" fails if $x is e.g. "-n". ksh has the - option to
> print to handle this case, but bash echo doesn't seem to. So how can
> I reliably output a variable whose contents are unknown?

Yes, in rewriting scripts from ksh to bash, I had to deal with
differences in echo.

You could try wrapping in double quotes. Oh wait you did.
But i tested on bash 3.2 and got:

# -bash 48 > s='-n ssssas'
# -bash 52 > echo $s
ssssas
# -bash 53 > echo "$s"
-n ssssas

So double quotes worked as it should have. (By making "$s" a single
token supplied as $1 to echo.)
What am I missing?

Anyway, suggestions:

How about using bash built in printf instead?

Or you could overload the builtin echo with an external echo that does
what you want by using the bash
'disable' command. (The gnu echo doesn't have a - for no more option
switches either.)

I believe when you build/install bash, you can disable echo (or indeed
many of the builtins) by default.
Don't Do Dat!

echo \ $s
or
echo ''" $s
will suppress interpretation of leading chars in $s as options to
echo, but they will introduce a leading space.
Something along these lines may work though.

Stilll....
echo "$s" worked ok for me. What am I missing?

Re: echoing arbitrary text in bash?

am 09.04.2008 10:50:06 von PK

andrej.panjkov@climatechange.qld.gov.au wrote:

> You could try wrapping in double quotes. Oh wait you did.
> But i tested on bash 3.2 and got:
>
> # -bash 48 > s='-n ssssas'
> # -bash 52 > echo $s
> ssssas
> # -bash 53 > echo "$s"
> -n ssssas
>
> So double quotes worked as it should have. (By making "$s" a single
> token supplied as $1 to echo.)
> What am I missing?

Try the above with s='-n' only.
Imho the best thing to do here is using printf.

--
All the commands are tested with bash and GNU tools, so they may use
nonstandard features. I try to mention when something is nonstandard (if
I'm aware of that), but I may miss something. Corrections are welcome.