0

What am I missing here?

I have created a simple array:

declare -a appArray=(
    "item1 -a -b"
    "item2 -c -d"
    )

If I echo this I can see it all

echo ${appArray[@]}

> item1 -a -b item2 -c -d

I then create a function as follows:

fc_DEBUG () { 
    if [ $1 -eq 1 ] ; then 
        echo $2; 
    fi; 
};

It is designed to sit in a bash script, and if I set a DEBUG variable it will echo the text back. So I can use it throughout the script without needing to manually add / remove things.

It works fine with basic data: e.g

fc_DEBUG $DEBUG "This is DEBUG text"

If I call this with the Array however, I only get a part of the Array.

fc_DEBUG $DEBUG "${appArray[@]}"

> item1 -a -b
3

${appArray[@]} gets expanded before fc_DEBUG runs. So the second argument the function sees, is the first of the array. To be explicit, the three arguments fc_DEBUG sees, are

$DEBUG "item1 -a -b" "item2 -c -d"

(replace $DEBUG with the words resulting from the split+glob operator applied to the actual value of $DEBUG (as you forgot to quote it)). In technical terms, the array is passed by value, not by reference.

fc_DEBUG () { 
    if [ "$1" -eq 1 ] ; then 
        shift
        echo "$@"
    fi
}

Now, the first argument is dropped from the argument list with shift, and the rest of all the arguments is printed.

Call it with a quoted array:

fc_DEBUG "$DEBUG" "${appArray[@]}"
  • That's great cheers. Good explanation too. – IGGt Jan 13 '16 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.