Skip to content

后台运行

& 符号

基本用法

bash
#!/bin/bash

# 后台运行进程
command &

输出重定向

bash
#!/bin/bash

# 后台运行并重定向输出
command > output.txt 2>&1 &

# 后台运行并重定向错误输出
command > /dev/null 2>&1 &

nohup 命令

基本用法

bash
#!/bin/bash

# 使用 nohup 后台运行
nohup command &

输出重定向

bash
#!/bin/bash

# 使用 nohup 后台运行并重定向输出
nohup command > output.txt 2>&1 &

# 使用 nohup 后台运行并重定向到 nohup.out
nohup command &

screen 命令

创建会话

bash
#!/bin/bash

# 创建会话
screen -S session_name

# 在会话中运行命令
command

# 分离会话(Ctrl+A, D)

重新连接会话

bash
#!/bin/bash

# 查看会话列表
screen -ls

# 重新连接会话
screen -r session_name

删除会话

bash
#!/bin/bash

# 删除会话
screen -X -S session_name quit

tmux 命令

创建会话

bash
#!/bin/bash

# 创建会话
tmux new -s session_name

# 在会话中运行命令
command

# 分离会话(Ctrl+B, D)

重新连接会话

bash
#!/bin/bash

# 查看会话列表
tmux ls

# 重新连接会话
tmux attach -t session_name

删除会话

bash
#!/bin/bash

# 删除会话
tmux kill-session -t session_name

实用示例

示例1:后台运行脚本

bash
#!/bin/bash

# 后台运行脚本
./script.sh &

# 后台运行脚本并重定向输出
./script.sh > output.txt 2>&1 &

示例2:使用 nohup

bash
#!/bin/bash

# 使用 nohup 后台运行脚本
nohup ./script.sh &

# 使用 nohup 后台运行脚本并重定向输出
nohup ./script.sh > output.txt 2>&1 &

示例3:使用 screen

bash
#!/bin/bash

# 创建 screen 会话
screen -S mysession

# 在会话中运行脚本
./script.sh

# 分离会话(Ctrl+A, D)

# 重新连接会话
screen -r mysession

示例4:使用 tmux

bash
#!/bin/bash

# 创建 tmux 会话
tmux new -s mysession

# 在会话中运行脚本
./script.sh

# 分离会话(Ctrl+B, D)

# 重新连接会话
tmux attach -t mysession

最佳实践

1. 使用 nohup

bash
# 好的做法
nohup command > output.txt 2>&1 &

# 不好的做法
command > output.txt 2>&1 &

2. 使用 screen

bash
# 好的做法
screen -S session_name

# 不好的做法
nohup command &

3. 使用 tmux

bash
# 好的做法
tmux new -s session_name

# 不好的做法
screen -S session_name

总结

后台运行的关键点:

  1. & 符号:后台运行进程
  2. nohup 命令:忽略 SIGHUP 信号后台运行
  3. screen 命令:创建和管理会话
  4. tmux 命令:创建和管理会话
  5. 实用示例:后台运行脚本、使用 nohup、使用 screen、使用 tmux
  6. 最佳实践:使用 nohup、使用 screen、使用 tmux

下一节我们将学习系统监控的使用。