There are instances where a function needs to execute and return to the caller and this works for me.

if tst; then
    echo "success"
    echo "failure"

function tst () {
    return 0;

However, I can't seem to be able to do it using shortcut syntax. I've tried many combinations of the following statement including testing if [[ tst = true ]] or if it = "0" but I haven't been able to figure it out.

[[ tst ]] && echo "success" || echo "failure"

What is the proper way to test the function in the if condition using bash shortcut syntax?


2 Answers 2


Assuming you want to use A && B || C, then simply call the function directly:

tst && echo "success" || echo "failure"

If you want to use [[, you'd have to use the exit value:

if [[ $? -eq 0 ]]
  • $? == 0 Is that a good idea? Jan 29, 2015 at 16:49
  • @HaukeLaging I think so. What do you suggest instead?
    – muru
    Jan 29, 2015 at 16:52
  • == is a pattern matching comparison. Arithmetic comparison is -eq (with [[ ]], too). So technically it works but rather as a coincidence. Jan 29, 2015 at 16:54
  • 2
    @HaukeLaging updated. But then again, I'd say if one is doing numeric comparison, (()) should be used instead.
    – muru
    Jan 29, 2015 at 16:56
  • Possible, too, but I don't remember ever having seen that. Jan 29, 2015 at 17:00

(this is not really an answer, more of a comment)

You have to be a bit careful about the a && b || c shortcuts:

  • if a returns success, then b is executed
  • if b subsequently returns an exit status, then c will be executed too.
$ [[ -f /etc/passwd ]] && { echo "file exists"; false; } || echo "file does not exist"
file exists
file does not exist

if a; then b; else c; fi is safer in this regard, in that c does not depend on b, only a

$ if [[ -f /etc/passwd ]];then { echo "file exists"; false; }; else echo "file does not exist"; fi
file exists
$ echo $?
  • if b subsequently returns a non-zero exit status, then c will be executed too. But you can do this to prevent possibly unwanted execution of c: a && { b; true; } || c or a && { b || true; } || c which are basically turning around your demonstration. Jan 29, 2015 at 22:37

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.