简体   繁体   中英

How to run a process in background and change directory in the same command-line

I would like to create a command that will change directory, run a process in the background and then return to the original directory. It is important for the process to be started from a specific directory (It uses the running directory for relative paths).

I tried running this, but got the following error:

cd ~/work; myapp &> /dev/null &; cd -
-bash: syntax error near unexpected token `;'

I can run either of the following commands.

# Without the "&" that cause the process to run in the background
cd ~/work; myapp &> /dev/null; cd -
# Without the " cd -" which returns my to the original directory
cd ~/work; myapp &> /dev/null &

The purpose of this, is to be able to add this command to my aliases.

As quoted from this GNU bash page,

A list is a sequence of one or more pipelines separated by one of the operators ; , & , && , or || , and optionally terminated by one of ; , & , or a newline.

Of these list operators, && and || have equal precedence, followed by ; and & , which have equal precedence. If a command is terminated by the control operator & , the shell executes the command asynchronously in a sub-shell. This is known as executing the command in the background

Which you can infer from above is that & is by itself a command separator just like ; . You just need to do

cd ~/work; myapp &> /dev/null & cd -
#                            ^^^ just acting as a command-separator

(or) group your commands into compound statements using {} as below

cd ~/work; { myapp &> /dev/null & }; cd -

Run the cd command and myapp in the same subshell and you do not need to cd back:

( cd ~/work; myapp &>/dev/null ) &

Parentheses, (...) , create a subshell. You can freely change directories ( cd ) or change the environment in a subshell and it will have no effect on the parent shell. Thus, there is no need to cd back afterward.

Example

Let's start from the directory /tmp/1 :

$ pwd
/tmp/1

Now, let's run cd and a sample command in a background shell and then check the directory again:

$ ( cd work; date &>/dev/null ) &
[1] 11942
$ pwd
/tmp/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM