Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Arithmetic Zero



On Tue, Mar 5, 2024 at 4:28 AM sergio <sergio@xxxxxxxxxxxxx> wrote:
>
> ```
> #!/bin/zsh -e
> (( test = 0 ))
> ```
>
> 2. How to do arithmetic evaluation properly in zsh sripts? postpend with
>   || true

When I end up in a situation like this, I use this pattern:

  (( expr, 1 ))

Although the more general patterns works here, too:

  list || true

I never use `set -e`, a.k.a. `setopt err_exit`, on its own, because
its behavior within functions is counter to what I need. In fact, I
don't think I ever wanted this option to behave the way it does in
functions. Let me show what I mean.

    set -e
    false
    launch-missiles

If you put these lines at the top level of a zsh script,
launch-missiles won't execute because the previous command (false)
fails. But if you put the same code in a function, this guarantee is
lost.

  % zsh -fc '
    foo() {
      set -e
      false
      print launch missiles
    }

    if ! foo; then :; fi
    foo || false
    foo && true
    print the end'

The output:

  launch missiles
  launch missiles
  launch missiles
  the end

This issue can be solved by turning on err_return together with err_exit.

  foo() {
    setopt local_options err_return err_exit
    false
    launch-missiles
  }

Now, we can either handle errors from the function gracefully:

  if ! foo; then
    do-something
  fi

Or we can let it take the default error handling action, which is to
exit the script:

  foo

In no case will the missiles launch.

Roman.




Messages sorted by: Reverse Date, Date, Thread, Author