← 返回命令列表

Linux command

wait 命令

文本

复制后可按需替换文件名、目录或参数。

常用示例

Wait for all background jobs

wait

Wait for a specific job

wait [pid]

Wait for multiple PIDs

wait [pid1] [pid2]

Wait for a job

wait %1

Wait for any single job

wait -n

Wait for any job and store its PID

wait -n -p completed_pid [pid1] [pid2]

Get exit status

command & wait $!; echo "Exit status: $?"

说明

wait is a shell builtin that pauses execution until specified background processes complete. It returns the exit status of the waited-for process. When given a PID, wait blocks until that process terminates. With a job specification (%1, %2, etc.), it waits for that specific job. Without arguments, it waits for all child processes. This is essential for scripts that spawn background processes and need to synchronize their completion or check their exit status. The special variable $! contains the PID of the last background process, commonly used with wait: command & pid=$!; wait $pid

参数

-n
Wait for any single job from the specified list (or all background jobs if none listed) to complete, and return its exit status. Available since Bash 4.3.
-f
Force wait for each process to actually terminate before returning, rather than returning when the job status changes (e.g., when stopped). Requires job control to be enabled.
-p _varname_
Assign the PID or job ID of the completed job to the variable _varname_. Most useful with -n to identify which job finished. Available since Bash 5.1.

FAQ

What is the wait command used for?

wait is a shell builtin that pauses execution until specified background processes complete. It returns the exit status of the waited-for process. When given a PID, wait blocks until that process terminates. With a job specification (%1, %2, etc.), it waits for that specific job. Without arguments, it waits for all child processes. This is essential for scripts that spawn background processes and need to synchronize their completion or check their exit status. The special variable $! contains the PID of the last background process, commonly used with wait: command & pid=$!; wait $pid

How do I run a basic wait example?

Run `wait` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does -n do in wait?

Wait for any single job from the specified list (or all background jobs if none listed) to complete, and return its exit status. Available since Bash 4.3.