Home > Blockchain >  bash - Can local variable assignment return false?
bash - Can local variable assignment return false?

Time:12-27

Say I have the following code where is_wednesday is a function that returns 0 on Wednesdays and 1 on other days.

print_wednesday() {
    is_wednesday && local WEDNESDAY="Yes!" || local WEDNESDAY="No!"
    echo "Is today Wednesday? $WEDNESDAY"
}

Is there a way that assigning a value to a local variable would return 1, which in this example would result in printing Is today Wednesday? No! on a Wednesday?

CodePudding user response:

Can local variable assignment return false?

The built-in local will:

  • return 2 when called with --help
  • return 2 when called with invalid -flags.
  • return 1 if not called inside a function
  • return 0 ever otherwise
  • (or the whole Bash process will terminate, in case of like "out of memory" errors)

Note that variable assignment (I mean, without local) will return the exit status of the last process executed. The following will print No:

true && WEDNESDAY="Yes$(false)" || WEDNESDAY="No"
echo "$WEDNESDAY"

Is there a way that assigning a value to a local variable would return 1, which in this example would result in printing Is today Wednesday? No! on a Wednesday?

No.


I would recommend:

  • separate local from assignment
  • do not use && || chain, always use if.
  • do not use upper case variables for local variables.
  • and to write the function in the following way:

print_wednesday() {
    local wednesday
    if is_wednesday; then
         wednesday="Yes"
    else
         wednesday="No"
    fi
    echo "Is today Wednesday? $wednesday!"
}

CodePudding user response:

I'm not sure I understand the overall objective/question since there are 2x variable assignments that have to be considered, and in each case a 'successful' assignment is going to lead to a different output (ie, No! or Yes!).

In the meantime I'd probably just simplify the current code a bit:

print_wednesday() {
    local WEDNESDAY="No!"
    is_wednesday && WEDNESDAY="Yes!"
    echo "Is today Wednesday? $WEDNESDAY"
}
  • Related