I’ve written small bash scripts before, but I bit off a little more this time, and I’m trying to program a little terminal game.

Anyway, I’ve run into a weird behavior. I have a function that, among other things, writes values to an array and returns either 0 or 1.

If I write echo "${name_of_array[@]}" inside the function, I see the contents of the array printed to standard output.

If I write echo "${name_of_array[@]}" outside the function immediately after executing the function, I see the contents of the array printed to standard output. (So, clearly the array is being treated as a global variable.)

But if I write the following, regardless of which value the function returns, nothing is printed to standard output but an empty line.

if ! name_of_function ; then
 echo "${name_of_array[@]}"
fi

Why is that the case? Doesn’t name_of_function get executed when evaluating the if statement? Is this some special case where all variables become local?

I realize I could just assign the function’s return value to a separate variable and then use that variable as the condition to the if statement, but it’s less elegant, and it doesn’t satisfy my curiosity. Is there any way to get the array out of the if statement alone?

It’s also possible I’m an idiot and my problem is just some random punctuation somewhere.

  • DirigibleProtein
    link
    fedilink
    English
    arrow-up
    2
    ·
    10 months ago

    What is the return value ( $? ) from the function?

    Not sure if if..then changes variable scope: it shouldn’t.

    I’ve always used [[..]] around tests, not sure if that changes variable scope.

    Where is the array first declared? Inside or outside the function?

    Not at my computer at the moment, so I can’t give you a better answer. I’ll play with the idea later today.

    • Ballig@programming.devOP
      link
      fedilink
      English
      arrow-up
      1
      ·
      10 months ago

      The return value is either 0 or 1.

      I don’t know enough about coding to know what a variable’s scope is. *SearXNG noises* You might be onto something. You think the function is being piped into a subshell?

      Brackets didn’t seem to help in my script; although maybe I should make a smaller test script just to rule out incompetence. (I’m guessing on the proper syntax for that, something like if ! [[ $(name_of_function "$arguments") ]] ; then, yes?)

      I’ve tried both versions. name_of_array=() in or out of the function, also declare -a -g name_of_array, if I’m remembering those arguments right, at the top of the script.

      Thanks for indulging my curiosity; I appreciate it.