7

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?

0

2 Answers 2

15

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 
    ...
6
  • $? == 0 Is that a good idea? Commented Jan 29, 2015 at 16:49
  • @HaukeLaging I think so. What do you suggest instead?
    – muru
    Commented 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. Commented 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
    Commented Jan 29, 2015 at 16:56
  • Possible, too, but I don't remember ever having seen that. Commented Jan 29, 2015 at 17:00
7

(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
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. Commented Jan 29, 2015 at 22:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .