Question

I have two identical Ubuntu 12.04 LTS systems. Today a shell script fails on one of the Ubuntu systems, even though it have not been modified for years, and was working a few hours ago. I was able to narrow the error down to this:

string='question mark: ?'
echo $string
question mark: n t

string='question mark: ?'
echo "$string"
question mark: ?

On the system where the shell script fails, '?' is replaced with 'n t' when the quotation marks are omitted. This is the result of the same test on the other identical system:

string='question mark: ?'
echo $string
question mark: ?

string='question mark: ?'
echo "$string"
question mark: ?

On this system the question mark is printed correctly, no matter if the quotation marks are omitted or not.

The shell script has not been modified for years, and the system has not been upgraded or modified in any way. The shell script was working fine hours ago, but suddenly it fails because of '?' is converted to 'n t', for no apparent reason.

I'm going crazy because of this, so I really hope someone has an idea why this could happen.

Thanks.

Was it helpful?

Solution

This is because you have files n and t in your working directory. ? gets replaced by any files with one character.

$ ls
a  t myfile

$ echo $string
question mark: a t

To solve it, double quote your variable when echoing:

$ echo "$string"
question mark: ?

In general, as devnull comments in Why does bash “echo [t]” result in “t” not “[t]”:

Shell Command Language tells that the following characters are special to the shell depending upon the context:

*   ?   [   #   ~   =   %

Moreover, following characters must be quoted if they are to represent themselves:

|  &  ;  <  >  (  )  $  `  \  "  '  <space>  <tab>  <newline>

So for example with * you get all the files:

$ string='question mark: *'

$ echo $string
question mark: a myfile t
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top