DEV Community

Jain Wun
Jain Wun

Posted on

4 2

[Linux] 讓程式在背景執行


讓command在背景跑

在要跑的指令結尾加上 &

jupyterlab &
Enter fullscreen mode Exit fullscreen mode

指令和 & 中間通常會空一格

同時又不會output

/path/to/your/script.sh > /dev/null 2>&1 &
Enter fullscreen mode Exit fullscreen mode

1 代表螢幕輸出,2 代表錯誤輸出

檢視背景執行的process

jobs
Enter fullscreen mode Exit fullscreen mode

Kill掉特定背景程式

kill %1
Enter fullscreen mode Exit fullscreen mode

最後面的數字是取決於jobs給的number (會從1開始)

[1]-  Running                 sleep 100 &
[2]+  Running                 sleep 200 &
Enter fullscreen mode Exit fullscreen mode

讓ssh連線detach後程序能繼續跑

接在已經背景執行的程序後

disown  -h  %1
Enter fullscreen mode Exit fullscreen mode

或是可以在下背景時同時搭配nohup

nohup jupyterlab &
Enter fullscreen mode Exit fullscreen mode

nohup會把原本output到terminal的東西給寫到nohup.out

如果你的指令會一直輸出內容,就有可能讓nohup.out 這個檔案異常巨大

可以搭配上面的> /dev/null 2>&1 會將所有輸出直接丟掉

nohup /path/to/your/script.sh > /dev/null 2>&1 &
Enter fullscreen mode Exit fullscreen mode

其他套件

還能用像是screen/ tmux來假裝連線一直都在

Reference

How to run a command in the background and get no output?

[shell] 2>&1 是什麼意思 @ 痞客興的部落格 :: 痞客邦 ::

How do I use the nohup command without getting nohup.out?

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay