如何在后台运行 shell 脚本?

如何在后台运行 shell 脚本?

如何在后台运行 shell 脚本?

答案1

根据你的需要,只需在命令末尾添加 &

script.sh &
command &

如果您在终端中运行它,然后想要关闭终端,请使用 nohup 或 disown

禁止

nohup script.sh &

否认

script &
disown

如果这不是您想要的,请更具体地提出您的问题。

答案2

如果您希望在关闭终端后保留脚本,另一种选择是使用setsid

setsid script.sh

nohup有关、disown&之间差异的更多信息setsidnohup、disown 和 & 之间的区别

答案3

您只需切换屏幕并在第二个屏幕上运行脚本即可。当脚本在第二个屏幕上启动时,切换回第一个屏幕并执行任何您想做的事情。第二个屏幕将作为额外的“终端窗口”在后台运行。即使您在第一个屏幕上关闭 ssh 连接,它也不会停止处理。

screen --help
Use: screen [-opts] [cmd [args]]
 or: screen -r [host.tty]

Options:
-4            Resolve hostnames only to IPv4 addresses.
-6            Resolve hostnames only to IPv6 addresses.
-a            Force all capabilities into each window's termcap.
-A -[r|R]     Adapt all windows to the new display width & height.
-c file       Read configuration file instead of '.screenrc'.
-d (-r)       Detach the elsewhere running screen (and reattach here).
-dmS name     Start as daemon: Screen session in detached mode.
-D (-r)       Detach and logout remote (and reattach here).
-D -RR        Do whatever is needed to get a screen session.
-e xy         Change command characters.
-f            Flow control on, -fn = off, -fa = auto.
-h lines      Set the size of the scrollback history buffer.
-i            Interrupt output sooner when flow control is on.
-l            Login mode on (update /var/run/utmp), -ln = off.
-ls [match]   or -list. Do nothing, just list our SockDir [on possible matches].
-L            Turn on output logging.
-m            ignore $STY variable, do create a new screen session.
-O            Choose optimal output rather than exact vt100 emulation.
-p window     Preselect the named window if it exists.
-q            Quiet startup. Exits with non-zero return code if unsuccessful.
-r [session]  Reattach to a detached screen process.
-R            Reattach if possible, otherwise start a new session.
-s shell      Shell to execute rather than $SHELL.
-S sockname   Name this session <pid>.sockname instead of <pid>.<tty>.<host>.
-t title      Set title. (window's name).
-T term       Use term as $TERM for windows, rather than "screen".
-U            Tell screen to use UTF-8 encoding.
-v            Print "Screen version 4.01.00devel (GNU) 2-May-06".
-wipe [match] Do nothing, just clean up SockDir [on possible matches].
-x            Attach to a not detached screen. (Multi display mode).
-X            Execute <cmd> as a screen command in the specified session.

ctrl+ ac将在活动屏幕会话中创建一个新的“窗口”。您可以在多个窗口之间切换(如 Ansgar 所示),使用ctrl+ an切换至下一个窗口,使用ctrl+ ap切换至上一个窗口。

ctrl+ a"将为您提供所有打开的窗口的列表。

更多的:https://superuser.com/questions/476709/quickly-switching-between-virtual-sessions-screen

答案4

tmux也是一种选择。

  1. tmux
  2. ./script.sh
  3. 前缀 +d

将会将其分离。

tmux a -t <number>

将恢复会话。

相关内容