1

I'm quite confused When I try to ouput some patterns with * in shell.The code is:

#!/bin/bash
for i in {1..10}
do
    tmpstr=""
    for ((c=1;c<=i;c++))
    do
            tmpstr=$tmpstr'*'
    done
    echo $tmpstr  #add some string after tmpstr will work
done

The output shows me the result of ls command in each line which is unexpected. And the code will works fine if I add any string after echo $tmpstr.For example,echo $tmpstr" " .So how to understand this?

1 Answer 1

4

Your script is generating the following for tmpStr

*
**
***
etc.

which results in the following echo statements

echo *
echo **
echo ***
etc.

The shell interprets the * as a wildcard and expands it by listing all the files in the current directory.

Note that if you put quotes around the shell variable:

echo "$tmpstr"  

The shell does not expand the wildcard characters and the output is

*
**
***
****
*****
******
*******
********
*********
**********
Sign up to request clarification or add additional context in comments.

8 Comments

I think this is the point.But a space after the string will make the wild card not work still is a mistery.
I don't follow. You state that the code works fine with echo $tmpStr" ". As you have written this, there is no wildcard, just a space.
I mean echo $tmpstr" " inside the first loop not the inner one.
@Young, well you can see for yourself by running echo * and then echo *" ". In the first case the shell treats * as a wildcard and expands it. In the second case the contiguous bits * and " " are concatenated into a single word * , and the * within the word is not expanded
@Young With echo * the final space is not treated as part of the "word" *; with echo *" " the double-quotes force the shell to treat it as a normal part of the word. If you had any files with names ending in space, echo *" " would list them, but you don't so the wildcard doesn't get expanded. Try this: touch 'foo '; echo *" " (and then try your script with the echo $tmpstr" " again).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.