2

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

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

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?

8

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:

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

(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 $?
1
  • 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. – Dennis Williamson Jan 29 '15 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.