Search code examples
bashshellsyntaxbackground-process

Run command in background in oneliner


I'm not sure what these types of statements are called, but essentially I'm trying to do this:

[ "string" = "somethingelse" ] && dofuncwhentrue "param" || dofuncwhenfalse "param" &

So either function should be run in the background, but I'm not sure where to place the & to achieve this.

Thanks!


Solution

  • If you try trivial versions of your one-liner, you'll see the behaviour.

    /bin/true && sleep 10 || sleep 10 &
    /bin/false && sleep 10 || sleep 10 &
    sleep 10 && sleep 10 || sleep 10 &
    

    In all cases you'll see that bash spawns everything, including the test, into the background immediately.

    If you really want the test to run in the foreground, you can structure the line with parentheses.

    sleep 10 && (sleep 10 &) || (sleep 10 &)
    

    As Inian has pointed out in a comment, using if would be more readable, but this is an interesting question!