我有两个相同的 Ubuntu 12.04 LTS 系统。今天,一个 shell 脚本在其中一个 Ubuntu 系统上失败了,即使它多年来没有被修改,并且在几个小时前就可以工作了。我能够将错误缩小到:
string='question mark: ?'
echo $string
question mark: n t
string='question mark: ?'
echo "$string"
question mark: ?
在 shell 脚本失败的系统上,'?'省略引号时,将替换为“n t”。这是在另一个相同系统上进行相同测试的结果:
string='question mark: ?'
echo $string
question mark: ?
string='question mark: ?'
echo "$string"
question mark: ?
在这个系统上,无论是否省略引号,问号都会正确打印。
shell脚本多年未修改,系统未进行任何升级或修改。 shell 脚本几小时前工作正常,但突然因为“?”而失败了。无缘无故地转换为“n t”。
我因此而发疯,所以我真的希望有人知道为什么会发生这种情况。
谢谢。
这是因为您的工作目录中有文件 n
和 t
。 ?
被任何具有一个字符的文件替换。
$ ls
a t myfile
$ echo $string
question mark: a t
要解决它,请在 echo
ing 时双引号您的变量:
$ echo "$string"
question mark: ?
一般来说,如devnull在 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>
因此,例如使用 *
,您将获得所有文件:
$ string='question mark: *'
$ echo $string
question mark: a myfile t