AIX Shell中的Echo表现出奇怪或任何原因

时间:2014-05-12 12:37:08

标签: shell echo aix

这是我试图读取文件的代码,其中包含" *"在每一行

文件名: test_new1.sh

#!/bin/sh
op=new_file.txt
echo $op
while read line
do
name=$line
echo $name
done < definition.txt

我的文件包含:

this is the file * having various chars

上述脚本的输出是:

this is the file definition.txt test_new1.sh having various chars

我知道同样的解决方案。如果我将echo $name更改为echo "$name"。它工作正常。

但我想知道为什么echo会以这种方式表现出来。

为什么它没有用双引号括起来列出我目录中的文件

我现在的O.S.是 AIX

1 个答案:

答案 0 :(得分:4)

这是因为*会扩展为当前目录中的所有文件。

您可以通过两种方式避免它:

  • 正如你所说,通过引用,使shell将其解释为字符串而不是参数:

    while read line
    do
      name=$line
      echo "$name"            <---- echo within quotes
    done < definition.txt
    
  • 停用noglobHow do I disable pathname expansion in bash?

    $ echo *
    one_file one_dir whatever
    
    $ set -o noglob              <--- disable
    $ echo *
    *
    
    $ set +o noglob              <--- enable again
    $ echo *
    one_file one_dir whatever
    

引自man bash

  

特殊模式字符具有以下含义:

     
      
  • 匹配任何字符串,包括空字符串。启用globstar shell选项时,*在路径名中使用   扩展上下文,用作单个模式的两个相邻*将匹配   所有文件和零个或多个目录和子目录。如果   后跟一个/,两个相邻的* s只匹配目录和   子目录。
  •