1

I have a variable $MOH in Bash which may contain words beginning with minus (-).

I don't want echo to interpret these words as parameters.

For most commands I do it like this:

cmd -- $MOH

But echo does not support --.

So I get a problem in this example:

MOH=-n
echo $MOH

Echo thinks -n is a parameter. But as I said I want to echo the variable as it is. (Please note that the value of $MOH is not known to me.)

So my question is: How to escape a variable for use in echo?

Also the escape function should be aware of future parameters in echo which are not known yet.

Edit: Thank you for editing. The question was already asked and the solution is to use printf instead of echo.

zomega
  • 1,538
  • 8
  • 26
  • 2
    This is addressed in the answer https://stackoverflow.com/a/52451742/14122 in the linked duplicate. – Charles Duffy Nov 22 '21 at 12:39
  • 2
    Also see [Why is printf better then echo?](https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo) on [unix.se], and [the POSIX standard for echo](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html), which itself recommends using printf instead (see in particular the APPLICATION USAGE and RATIONALE sections). – Charles Duffy Nov 22 '21 at 12:41

1 Answers1

3

It is a known limitation of echo, and actually it is better not to use echo in the first place but rather printf (see below).

Also, beware that there are some quoting issues in your command, one should always use "$MOH" instead of $MOH. Otherwise, "bad things happen" if the variable contains spaces or * characters… For details on this issue, see https://mywiki.wooledge.org/Quotes

Hence the command:

MOH='-n'
printf '%s\n' "$MOH"
ErikMD
  • 13,377
  • 3
  • 35
  • 71