nushell

How to get rid of error messages in nushell?


In Bash I would do something like

...
...
if ! cd non_exist_dir > /dev/null 2>&1; then
  echo "error in cd"
  return 1
fi
...
...

How would I do that in idiomatic nushell ?
Especially, how can I get rid of the annoying error message displayed by nushell because the directory doesn't exist ?
Bonus points if I could get something like a "return" command, which seems to be missing in nushell.


Solution

  • Nushell 0.72 introduces try/catch blocks which can suppress or replace the error handling for Nushell builtins. For your example:

    try {
        cd non_exist_dir
    } catch {
        print -e "error in cd"
    }
    

    As for the other part of your question, a return code would only seem to be useful if are returning to a non-Nushell process. Any error handling from within Nushell can use Nushell errors and try/catch blocks.

    But if you are returning to a non-Nushell process, then you can use the exit <status_code> builtin.

    This would only work in either:

    However, a simple cd could never work in either case, since both cases start a new Nushell shell (try saying that 10 times real fast), and when that shell exits, the environment will be returned to its entry state (even with def-env).

    But if you are doing something after the cd, then it would make sense to include this in a script. For example, a silly_cd.nu (silly, because it's pretty useless other than as a demonstration of exit):

    #!/usr/bin/env nu
    def main [d?: string] {
        if ($d == null) {
            # Prevent sourced function from exiting Nushell
            return
        }
        try {
            cd $d
        } catch {
            print -e "Error in cd"
            exit 1
        }
        ls
    }