2

Are there any elegant ways to write bash functions in .bashrc/.bash_profile which return as soon as a command returns error?

I have been using this format for some time but I was wondering if there are better ways as having || return 1 on every line doesn't look great.

function doCommands() {
    command1 || return 1 # return if command1 returns error
    command2 || return 1
    command3 || return 1
}

Thank you.

user674669
  • 10,681
  • 15
  • 72
  • 105
  • https://stackoverflow.com/questions/2870992/automatic-exit-from-bash-shell-script-on-error – yoki Mar 13 '18 at 05:43
  • @yoki, Most of the answers in your link are about scripts. My question is about a bash function. If I use set -e in a script, my terminal/iterm window closes. – user674669 Mar 13 '18 at 05:52
  • 2
    @user674669; You could take a look at this - https://stackoverflow.com/questions/30488698/how-to-make-a-bash-function-return-1-on-any-error – Inian Mar 13 '18 at 05:54
  • 1
    I think explicit return are better so that return points can be easily seen, @thatotherguy maybe you mean `cmd1 && cmd2 && cmd3`, @Inian this work only if function has no side effect (global variable assignment), knowing that variable assignment is a fast way to pass result as return can only give exit code (numbers). – Nahuel Fouilleul Mar 13 '18 at 08:37

0 Answers0