Search code examples
bashsubshell

Two ways of running a command checked with if


Both of these work. The first is shorter, but I'm guessing the second is safer or better - running the command inside $()

If so, could someone explain why the second is safer, better, etc.

if my_function "something" ; then ...

if $(my_function "something"); then ...


Solution

  • The first is usually what you want. The first one executes the function, checks its exit status, and runs the then section if the status indicates the function succeeds.

    The second (with $( )) runs the function, captures whatever your function prints to stdout, and then tries to execute that output as another command. If it doesn't output anything, nothing gets run, so the then section gets executed if your function succeeds (just like the first version). On the other hand, if it does output anything, that gets run as another command, and the then section gets run if that succeeds. If what it printed wasn't a valid command, that counts as failure.

    So, the question is, does your function print a command you want executed? If so, use the second form. It not, use the first.