What does “&” at the end of a linux command mean?

2019-01-03 09:20发布

I am a system administrator and I have been asked to run a linux script to clean the system.

The command is this:

perl script.pl > output.log &

so this command is ending with a & sign, is there any special significance of it?

I have basic knowledge of shell but I have never seen this before.

标签: linux shell unix
4条回答
SAY GOODBYE
2楼-- · 2019-01-03 09:52

When not told otherwise commands take over the foreground. You only have one "foreground" process running in a single shell session. The & symbol instructs commands to run in a background process and immediately returns to the command line for additional commands.

sh my_script.sh &

A background process will not stay alive after the shell session is closed. SIGHUP terminates all running processes. By default anyway. If your command is long-running or runs indefinitely (ie: microservice) you need to pr-pend it with nohup so it remains running after you disconnect from the session:

nohup sh my_script.sh &

EDIT: There does appear to be a gray area regarding the closing of background processes when & is used. Just be aware that the shell may close your process depending on your OS and local configurations (particularly on CENTOS/RHEL): https://serverfault.com/a/117157.

查看更多
小情绪 Triste *
3楼-- · 2019-01-03 09:54

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action. Now if you do- $ command & Then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

查看更多
走好不送
4楼-- · 2019-01-03 09:58

The & makes the command run in the background.

From man bash:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

查看更多
等我变得足够好
5楼-- · 2019-01-03 09:58

In addition, you can use the "&" sign to run many processes through one (1) ssh connections in order to to keep minimum number of terminals. For example, I have one process that listens for messages in order to extract files, the second process listens for messages in order to upload files: Using the "&" I can run both services in one terminal, through single ssh connection to my server.


*****I just realized that these processes running through the "&" will also "stay alive" after ssh session is closed! pretty neat and useful if your connection to the server is interrupted**

查看更多
登录 后发表回答