LinuxCommandLibrary

do

Execute commands within loop constructs

TLDR

View documentation for the for keyword

$ tldr for
copy

View documentation for the while keyword
$ tldr while
copy

View documentation for the select keyword
$ tldr select
copy

View documentation for the until keyword
$ tldr until
copy

SYNOPSIS

for name [in words]; do commands; done
while list; do commands; done
until list; do commands; done

DESCRIPTION

The do keyword is a reserved word in POSIX-compliant shells like Bash, used in control structures such as for, while, and until loops to mark the start of the loop's command block. It pairs with done to enclose repeated commands.

In scripting, it enables automation of repetitive tasks. For example, a for loop iterates over a list, executing commands between do and done for each item. While loops use do after a condition test, repeating until false.

Though not an executable command (type do shows 'reserved word'), it's essential for shell programming on Linux. It supports compound commands, functions, and subshells. Misuse, like redefining do, breaks scripts. Portable across sh, bash, zsh, ksh.

CAVEATS

Reserved word; cannot alias, function, or use as command/variable name. Requires matching done. Indentation optional but recommended for readability.

BASIC EXAMPLE

for i in {1..3}; do
echo "Number: $i";
done

Output:
Number: 1
Number: 2
Number: 3

WHILE EXAMPLE

count=0
while [ $count -lt 3 ]; do
echo $count
((count++))
done

HISTORY

Originated in Bourne shell (1977) by Stephen Bourne at Bell Labs. Standardized in POSIX.1-1988, evolved with shell enhancements in Bash (1989+).

SEE ALSO

bash(1), sh(1), zsh(1), ksh(1)

Copied to clipboard