2

I want to write an alias that's something like:

alias baz="false || echo bar"

(It's not actually false, it's a command that can fail). However, I want to pass the failed status code through to the next invoker. In other words, here's the current behavior:

$ false; echo $?
1
$ false || echo foo; echo $?
0

I want to do a different operation that has the same behavior in every respect as false || echo foo, except when I do echo $? it would return 1.

Note: I expect the echo foo bit to essentially always succeed.

  • false || echo foo && false – Kusalananda Apr 13 '17 at 19:52
  • Or at a certain level of not-tcsh complexity instead use a function, and save the return status and return it later on after other codes. – thrig Apr 13 '17 at 19:56
  • @Kusalananda of course. this is what i get for not eating my wheaties this morning. If you turn that into an answer I'll give you rep – durron597 Apr 13 '17 at 19:59
  • 2
    false || ( ret=$?; do_stuff; exit $ret ) – DopeGhoti Apr 13 '17 at 20:34
6

A function to save the return value of a command isn't that complicated:

f() {
    some-command-that-can-fail
    retval=$?
    if [ "$retval" != 0 ] ; then
         echo the command failed
    fi
    return $retval
}

If you don't care about the exact return value, but just want a nonzero return code, this would work:

somecmd || ( echo it failed ; false )

You need the subshell (or a compound block) to only run the final false if the original command fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.