help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Simple echo is printing the wrong value


From: Bill Gradwohl
Subject: Re: [Help-bash] Simple echo is printing the wrong value
Date: Wed, 4 Apr 2012 08:54:25 -0600

Eric:

I'm reusing this thread because what follows builds on the previous.

#!/bin/bash

rm -rf junkdir
mkdir junkdir
cd junkdir
touch '*'
touch 'X'

func(){
echo $# "$@"
}

for file in *; do
   echo ${file}
   func ${file}
   case ${file} in
      '*')
       echo got asterisk
      ;;
      *)
       echo got something else
      ;;
   esac
   echo ===================
   echo "${file}"
   func "${file}"
   case "${file}" in
      '*')
       echo got asterisk
      ;;
      *)
       echo got something else
      ;;
   esac
   echo ===================
done

cd ..
rm -rf junkdir

echo ===================

case '* X' in
   '*')
    echo got asterisk
   ;;
   *)
    echo got something else
   ;;
esac



Produces:


address@hidden 24.testing# ./junk
* X
2 * X
got asterisk
===================
*
1 *
got asterisk
===================
X
1 X
got something else
===================
X
1 X
got something else
===================
===================
got something else



The for loop sees an unquoted asterisk so that expands to the files in the directory = 'x' 'X'
The for loop therefore has 2 elements in the list to work on, the first being *.
Bash provides the value of file which is an asterisk to the echo statement.
The echo sees an unquoted asterisk, so Bash expands the * to '*' and 'X' again, and the output confirms that.
The function call also confirms that. 2 passed parameters.
The case statement obviously only sees the * as a literal. Why?

Why do some things get 2 cracks at expansion and others only 1?

The last solitary case statement shows that the one in the loop only saw the asterisk. If it saw '*' 'X', that's an error, so that can't be it.

--
Bill Gradwohl


reply via email to

[Prev in Thread] Current Thread [Next in Thread]