Pregunta

Here's a code in which i am trying to read a file having "*" in every line

File name : test_new1.sh

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

My file contains :

this is the file * having various chars

the output of the above script is :

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

i know the solution to the same . If i change echo $name to echo "$name" . It works fine .

But i would like to know why does echo behave this way .

why does it list the files in my directory when not enclosed in double quotes ?

my current O.S. is AIX

¿Fue útil?

Solución

This is because * gets expanded as all files in your current directory.

You can avoid it with two ways:

  • As you said, by quoting, which makes shell interpret it as a string and not a parameter:

    while read line
    do
      name=$line
      echo "$name"            <---- echo within quotes
    done < definition.txt
    
  • Deactivating noglob: How 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
    

Quoting from man bash:

The special pattern characters have the following meanings:

  • Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top