NewStack
NewStack

Reputation: 39

Strange Behavior in Bash For Loop

Given the following code, BASH's output is unexpected for me and I'm looking for possible solutions (I've tried changing the way I'm quoting but that doesn't seem to affect anything to produce the desired result):

Testing File:

            #!/bin/bash
            . FindMissingSettings.function

            Settings[0]="FirstSetting"
            Settings[1]="SecondSetting"
            Settings[2]="ThirdSetting"
            ThisFile="ThisFile"

            find_missing_settings "${Settings[@]}" "$ThisFile"

The included FindMissingSettings.function:

            #!/bin/bash
            find_missing_settings () {
                Settings=("$@")
                File=$2
                for Setting in "${Settings[@]}"; do
                        echo "$Setting"
                        echo "1"
                    done
                echo "$File"
                echo "2"
            }

I expected the output from this script and the included function to be:

 FirstSetting
 1
 SecondSetting
 1
 ThirdSetting
 1
 ThisFile
 2

However this was the result I received:

 FirstSetting
 1
 SecondSetting
 1
 ThirdSetting
 1
 ThisFile
 1
 SecondSetting
 2

Why is this and what can I do to provide the desired result? Thank you!

Upvotes: 0

Views: 53

Answers (1)

ZiGaelle
ZiGaelle

Reputation: 744

In your find_missing_settings function, in your variable Setting, you have all the given inputs (FirstSetting, Second Setting, ThirdSetting, ThisFile). That's why it print it all with during the loop. Then it print the 2nd setting in the list, so SecondSetting

To fix this, you can put ThisFile as first parameter of the function:

find_missing_settings "$ThisFile" "${Settings[@]}" 

And change in the find_missing_settings function how you get the inputs:

    Settings=("${@:2}")
    File=$1

The :2 ask to get the inputs starting from the 2nd one only, and you put the first one (ThisFile) in the variable File

Upvotes: 1

Related Questions