Sunday, October 9, 2022

[SOLVED] How to use += operator in shell script?

Issue

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:

*
* * 
* * *
* * * *
* * * * *

Solution

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.



Answered By - Mark Reed
Answer Checked By - Robin (WPSolving Admin)