this post was submitted on 26 Feb 2024
0 points (NaN% liked)

Shell Scripting

21 readers
1 users here now

From Ash, Bash and Csh to Xonsh, Ysh and Zsh; all shell languages are welcome here!

Rules:
  1. Follow Lemmy rules!
  2. Posts must relate to shell scripting. (See bottom of sidebar for more information.)
  3. Only make helpful replies to questions. This is not the place for low effort joke answers.
  4. No discussion about piracy or hacking.
  5. If you find a solution to your problem by other means, please take your time to write down the steps you used to solve your problem in the original post. You can potentially help others having the same problem!
  6. These rules will change as the community grows.

Keep posts about shell scripting! Here are some guidelines to help:


In general, if your submission text is primarily shell code, then it is welcome here!

founded 1 year ago
MODERATORS
 

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.

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here