Create a background process in bash function

I am working on writing a Bash function to start a server that needs to be run from a specific folder, but I do not want this server to affect my current work. I wrote the following:

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

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

Is there anything I can do to run ${SERVERCOMMAND}in the background, still using pushd and popd, to make sure I get back to my current directory?

Edit: output echo ${SERVERCOMMAND}since it was requested:

yeti --server --port 8727

Error message:

-bash: syntax error near unexpected token `;'
+3
source share
3

$SERVERCOMMAND? .

pushd/cd pushd:

pushd $TRUNK
$SERVERCOMMAND &
popd

, cd :

(cd $TRUNK; $SERVERCOMMAND &)
+11

cd -

cd $TRUNK
$SERVERCOMMAND &
cd -
+3

${SERVERCOMMAND} , bash . , , .

, :

  • ${TRUNK} . , bash cd.
  • cd ${TRUNK} . , bash .
  • , ${SERVERCOMMAND} (, ).
  • Keyword functionand crew pushdand popd bash-specific, so this code will not run in the POSIX shell.

Here's a more secure, POSIX compliant rewriter:

log() { printf '%s\n' "$*"; }
error() { log "ERROR: $*" >&2; }
fatal() { error "$*"; exit 1; }

startsrv() {
    (
        cd "${TRUNK}" || fatal "failed to cd to '${TRUNK}'"
        set -- ${SERVERCOMMAND}
        command -v "$1" >/dev/null || fatal "command '$1' not found"
        command "$@" &
    ) || exit 1
}
+2
source

All Articles