bash - 无缘无故的shell脚本问题

标签 bash ubuntu-12.04

<分区>

我有两个相同的 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”。

我因此而发疯,所以我真的希望有人知道为什么会发生这种情况。

谢谢。

最佳答案

这是因为您的工作目录中有文件 nt? 被任何具有一个字符的文件替换。

$ ls
a  t myfile

$ echo $string
question mark: a t

要解决它,请在 echoing 时双引号您的变量:

$ echo "$string"
question mark: ?

一般来说,如devnullWhy 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

关于bash - 无缘无故的shell脚本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23512257/

相关文章:

linux - Bash Script 添加、删除、用户、目录和文件

linux - 从 runuser 命令传播退出代码

java - 在预先录制的 ONI 文件上使用 openNI 进行骨骼跟踪时出现异常

sdl - 如何在 Ubuntu 12.04.1 LTS 上安装 SDL_image?

bash - 如何编写每 10 分钟自动运行一次的 bash 脚本?

bash - 如何在 linux 上列出非空子目录?

macos - Mac 上的默认终端 $PATH 位于何处?

java - Bash 脚本的行为不同于 Docker 运行命令而不是容器本身?

python - Kivy Hello World 不工作

linux - 在VMware中安装Ubuntu 12.04