0

I have a very simple code as below.

myVal=""
for ((i=1 ;i<=5 ;i++))
do
    myVal+=" * "
    echo $myVal
done

Issue is:

  1. I am not able to use += in this shell script code.
  2. When I am assing a * in varibale, it prints all files which are in my working directory.

Output:

*
* * 
* * *
* * * *
* * * * *
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50

1 Answers1

1

Your issue has nothing to do with +=, which is working fine; your myVal var has a sequence of asterisks, exactly as intended. But when you echo it, those asterisks are expanded into the file list. To prevent that, you need to quote the expansion:

echo "$myVal"

You should always quote expansions in the shell, unless you have a very good specific reason not to. Basically, any time you see a $ without a double quote in front of it, you should stop and think and make sure you know what's happening in that code.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175