简体   繁体   English

如何在后台运行进程并在同一命令行中更改目录

[英]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, 从这个GNU bash页面引用,

A list is a sequence of one or more pipelines separated by one of the operators ; list是由一个运算符分隔的一个或多个管道的序列; , & , && , 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. 如果命令由控制操作符&终止,则shell在子shell中异步执行命令。 This is known as executing the command in the background 这称为在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: 在相同的子shell中运行cd命令和myapp ,你不需要回cd

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

Parentheses, (...) , create a subshell. 括号, (...) ,创建一个子shell。 You can freely change directories ( cd ) or change the environment in a subshell and it will have no effect on the parent shell. 您可以自由更改目录( cd )或更改子shell中的环境,它将不会影响父shell。 Thus, there is no need to cd back afterward. 因此,没有必要对cd回来之后。

Example

Let's start from the directory /tmp/1 : 让我们从目录/tmp/1

$ pwd
/tmp/1

Now, let's run cd and a sample command in a background shell and then check the directory again: 现在,让我们在后台shell中运行cd和一个示例命令,然后再次检查目录:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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