brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Ctrl-Z pauses a running command, bg sends it to the background and fg brings it back

Linux
~/tips/tip-bash-ctrl-z-bg-fg-jobs

Ctrl-Z # pause the running command

Pauses a command that blocks your terminal and lets it continue in the background.

You start a big copy, it takes over the terminal, and you realise you want the prompt back. Cancelling it with Ctrl-C and starting over with an & at the end is the reflex. Bash has a nicer way, and it has been there since forever.

Press Ctrl-Z while the command runs. Bash stops the process (paused, not killed) and gives you the prompt back. Then you decide what happens to it:

Ctrl-Z      # pause the running command
bg          # let it carry on in the background
jobs        # list your jobs with their numbers
fg %1       # bring job 1 back to the foreground

An example with a slow copy:

$ cp -r /mnt/user/media/photos /mnt/disks/backup/
^Z
[1]+  Stopped                 cp -r /mnt/user/media/photos /mnt/disks/backup/
$ bg
[1]+ cp -r /mnt/user/media/photos /mnt/disks/backup/ &
$ df -h /mnt/disks/backup

The copy carries on while you check the free space. fg without a number takes the current job, the one marked with a + in the jobs list. You can also type %1 on its own as a short form of fg %1, or %cp to pick the job whose command starts with cp.

Two caveats. A job you only stopped and never sent on with bg does nothing at all, so a forgotten Ctrl-Z can leave a half-finished copy sitting there. Bash does warn you when you try to exit with stopped jobs; a second exit ends them. And background jobs still belong to this terminal: close it and bash sends them a hangup signal. For something that must survive the session, I’d start it in tmux or screen from the beginning, because job control only moves work around inside one shell.

Further reading: Job control basics (GNU Bash manual), bash(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link