Skip to main content

πŸ“˜ ** Command Chaining using cmd & (Background Execution)**


🎯 What You Will Learn​

  1. Understand how the ampersand (&) operator works in Bash.
  2. Learn how to run commands in the background, freeing up your terminal for other tasks.
  3. Explore process control β€” how to list, manage, and bring back background jobs.
  4. Apply background execution in WordPress VPS operations, server maintenance, and automation scripts.
  5. Learn how background tasks interact with system resources and shell sessions.
  6. Identify and avoid common mistakes (like detached or orphaned jobs).

1. 5W + 1H Framework​

ElementDescription
WhatThe & operator runs a command in the background, allowing the shell to continue executing the next command immediately.
WhyTo save time and multitask, especially when a command takes a long time to finish (e.g., large backups, scans, updates).
WhoLinux administrators, DevOps engineers, and WordPress VPS managers managing multiple server tasks.
WhenWhen a command doesn’t require immediate terminal output β€” e.g., cron jobs, backups, or log processing.
WhereIn CLI, scripts, or system automation tasks that handle long-running or non-interactive commands.
HowAppend & at the end of a command: command &

2. Prerequisites​

  • Basic understanding of:
  • Bash CLI
  • Foreground vs background process behavior
  • Process IDs (PID)
  • Optional: jobs, fg, bg, and ps utilities installed (they’re standard in Bash).

3. Core Syntax & Concept ( Revised )​

#Syntax FormulaExample CommandPurpose / UsageBehavior / Notes
1command &sleep 60 &Run a single command in background.Shell prints job ID and PID, returns prompt immediately.
2cmd1 & cmd2tar -czf backup.tar.gz /var/www/html & echo "Backup started"Start cmd1 in background, then instantly run cmd2.cmd1 continues independently while cmd2 executes.
3{ cmd1 & cmd2 & }{ sleep 10 & sleep 5 & }Launch multiple tasks simultaneously.Both run in parallel; shell returns after both complete or are disowned.
4( cmd1 & ) ; cmd2( mysqldump -u root -p wpdb > backup.sql & ) ; echo "Dump started"Run background job inside a subshell, then a foreground command.Subshell isolates environment; cmd2 executes immediately after.
5nohup command &nohup wp plugin update --all > /root/logs/wpupdate.log 2>&1 &Execute background job immune to terminal hang-ups.Continues after SSH logout; redirect output to file for logs.
6nice -n 10 command &nice -n 10 tar -czf backup.tar.gz /var/www/html &Run a background job with lower CPU priority.Helps prevent I/O or CPU starvation on busy servers.
7command > log.txt 2>&1 &clamscan -r /var/www/html > /root/logs/scan.log 2>&1 &Send stdout and stderr to log file while running in background.Keeps terminal clean and stores output for review.

4. Conceptual Flow​

# Example 1
sleep 60 &

Expected Output:

[1] 2457

Explanation:

  • [1] β†’ Job number assigned by shell.
  • 2457 β†’ Process ID (PID).
  • The shell immediately returns to the prompt while the process runs in background.

# Example 2
tar -czf /root/wpbackup.tar.gz /var/www/html & echo "Backup started..."

Expected Output:

[1] 2498
Backup started...

Explanation:

  • Backup starts in the background; shell moves on instantly.
  • Ideal for large WordPress directories.

# Example 3 (with nohup)
nohup wp plugin update --all > /root/logs/wpupdate.log 2>&1 &

Expected Output:

[1] 2520
appending output to 'nohup.out'

Explanation:

  • Runs even if SSH session disconnects.
  • Redirects output to /root/logs/wpupdate.log.

5. WordPress VPS Use Cases​

ScenarioExample CommandDescription
1. Background Plugin Updatewp plugin update --all &Updates all plugins in background while continuing other work.
2. Long Backup Processtar -czf /root/wpbackup.tar.gz /var/www/html &Create full backup without blocking shell.
3. MySQL Dumpmysqldump -u root -p wpdb > /root/backup.sql &Backup database in background.
4. Log Rotationlogrotate /etc/logrotate.conf &Run log rotation while performing updates.
5. Virus Scanclamscan -r /var/www/html &Perform malware scan in background.
6. Remote Deploymentrsync -avz /var/www/html root@backup:/mirror/ &Sync site to remote backup server in background.

6. Best Practices​

PracticeDescription
βœ… Always monitor jobsUse jobs or ps to check running background processes.
βœ… Redirect outputExample: command > output.log 2>&1 &
βœ… Use nohup for SSHPrevents process termination when SSH disconnects.
βœ… Assign logs for each background taskEasier debugging and validation.
⚠️ Avoid running too many at onceCan overload CPU or disk I/O.
βš™οΈ Combine with nice or ****ioniceControl resource priority. Example: nice -n 10 tar -czf backup.tar.gz /var/www/html &

7. Process Management Essentials​

CommandDescriptionExample
jobsLists all background jobs with job numbers.jobs
fg %1Bring job #1 to foreground.fg %1
bg %1Resume a stopped job in background.bg %1
kill %1Terminate job #1.kill %1
`ps auxgrep process`Check background process status.
disown %1Detach job so it won’t stop when terminal closes.disown %1

8. Common Mistakes & Fixes​

MistakeExampleProblemFix
Forgetting output redirectionwp plugin update --all &Output floods the screen.Redirect: wp plugin update --all > /root/logs/wpupdate.log 2>&1 &
Running too many jobsfor i in {1..20}; do sleep 100 & doneSystem overloads.Limit background jobs with wait or job control.
Losing jobs on disconnectSSH closes, job stopsUse nohup or screen/tmux
Forgetting to stopBackground process keeps runningCheck with jobs, then kill %1

9. Troubleshooting Matrix​

IssueCauseSolution
Background job stops after logoutTerminal session endedUse nohup, screen, or tmux.
Can’t find running jobJob detached or PID unknownUse `ps aux
Too many background jobsOverloaded CPU or I/OLimit concurrency using wait.
Output missingNot redirectedAlways specify > logfile 2>&1.

10. Quick Lab: Practice on VPS​

Objective: Backup WordPress files while running other commands.

tar -czf /root/wpbackup.tar.gz /var/www/html > /root/logs/backup.log 2>&1 &
echo "Backup started in background..."
sleep 5
jobs

Expected Output:

Backup started in background...
[1]+ Running tar -czf /root/wpbackup.tar.gz /var/www/html > /root/logs/backup.log 2>&1 &

Now check progress:

ps aux | grep tar

Expected Output:

root 3130 95.0 0.5 22000 5400 pts/0 R 14:35 0:20 tar -czf /root/wpbackup.tar.gz /var/www/html


11. Combined Example with AND, OR, and &​

wp plugin update --all && echo "βœ… Update done" || echo "❌ Failed" & disown

Behavior:

  • Update runs in background.
  • Success/failure message logged.
  • Process detached safely from terminal. Expected Output:
[1] 3421
βœ… Update done


12. Cheat Sheet​

PatternMeaningExample
cmd &Run command in backgroundsleep 60 &
cmd1 & cmd2Run first in background, continue with nexttar -czf site.tar.gz /var/www/html & echo "Done"
nohup cmd &Run in background, persist after logoutnohup backup.sh &
jobsList background tasksjobs
fg %1Bring job to foregroundfg %1
disown %1Detach job permanentlydisown %1

13. Mini-Quiz​

  1. What does cmd & do? β†’ Runs the command in the background, freeing the terminal.
  2. What’s the difference between ; and &? β†’ ; runs sequentially in foreground; & runs concurrently in background.
  3. How do you view running background jobs? β†’ Use jobs.
  4. How can you ensure a background process continues after SSH logout? β†’ Use nohup or disown.
  5. What’s the role of the number in [1] 2457? β†’ Job number and PID assigned by Bash.