Search code examples
bashshellunixbash-function

Spawn a background process in a bash function


I am working on writing a Bash function to start a server that needs to be started from a certain folder, but I don't want starting this server to impact my current work. I've written the following:

function startsrv {
        pushd .
        cd ${TRUNK}
        ${SERVERCOMMAND} & 
        popd
}

My variables are all set, but when this executes, I get an error regarding an unexpected semicolon in the output, it appears that Bash is inserting a semicolon after the ampersand starting ${SERVERCOMMAND} in the background.

Is there anything I can do to start ${SERVERCOMMAND} in the background while still using pushd and popd to make sure I end up back in my current directory?

Edit: Output of echo ${SERVERCOMMAND}, since it was requested:

yeti --server --port 8727

Error message:

-bash: syntax error near unexpected token `;'

Solution

  • What is the value of $SERVERCOMMAND? You must have a semi-colon in it.

    For what it's worth you can simplify the pushd/cd to one pushd:

    pushd $TRUNK
    $SERVERCOMMAND &
    popd
    

    Or create a subshell so the cd only affects the one command:

    (cd $TRUNK; $SERVERCOMMAND &)