The do keyword in Linux begins a loop structure that executes commands until a specified condition is met. If you have ever wondered what does do in linux, this guide will break it down with clear examples. You will learn how to use do in bash loops for scripting and automation.
The do command is not a standalone utility but a key part of loop constructs like for, while, and until. It tells the shell where the block of commands starts. Without do, loops would not know what to execute repeatedly.
Think of do as the opening bracket for a loop body. It pairs with done to define the scope. This simple structure makes Linux scripting powerful and predictable.
What Does Do In Linux
The exact keyword “What Does Do In Linux” refers to understanding how the do keyword functions within shell scripts. It is essential for writing loops that automate repetitive tasks. Let us explore its syntax and usage in detail.
In bash, do appears after the loop condition. For example, in a for loop, you write for i in list; do commands; done. The do keyword signals the start of the command block.
Basic Syntax Of Do In Loops
The syntax is consistent across loop types. Here is the general pattern:
for variable in list; dowhile condition; dountil condition; do
Each loop ends with done. The commands between do and done execute repeatedly based on the condition.
Example With For Loop
Run this in your terminal:
for i in 1 2 3; do
echo "Number: $i"
done
Output:
Number: 1
Number: 2
Number: 3
The do keyword makes the loop execute the echo command for each value.
Example With While Loop
Here is a counter example:
count=1
while [ $count -le 3 ]; do
echo "Count: $count"
((count++))
done
Output:
Count: 1
Count: 2
Count: 3
Notice do appears right after the condition. It is mandatory for the loop to work.
Common Mistakes With Do
Beginners often forget the semicolon before do when writing on one line. The correct format is for i in list; do. Without the semicolon, bash throws a syntax error.
Another mistake is placing do on a new line without a semicolon. That is fine if you break the line correctly:
for i in 1 2 3
do
echo "Number: $i"
done
Both styles work, but the one-line version is common in scripts.
Using Do In Until Loops
The until loop runs while the condition is false. The do keyword works the same way:
num=1
until [ $num -gt 3 ]; do
echo "Num: $num"
((num++))
done
Output:
Num: 1
Num: 2
Num: 3
Here, do starts the block that runs until the condition becomes true.
Do With Select Loop
The select loop also uses do. It creates a menu from a list:
select option in "Start" "Stop" "Exit"; do
case $option in
Start) echo "Starting...";;
Stop) echo "Stopping...";;
Exit) break;;
esac
done
Without do, the select loop would not know where the menu actions begin.
Do In Nested Loops
You can nest loops, and each inner loop has its own do and done. This is common for processing multidimensional data:
for i in 1 2; do
for j in a b; do
echo "$i$j"
done
done
Output:
1a
1b
2a
2b
Each do belongs to its respective loop. Indentation helps readability but is not required.
Do With Break And Continue
Inside a loop, break exits the loop, and continue skips to the next iteration. Both work within the do...done block:
for i in 1 2 3 4 5; do
if [ $i -eq 3 ]; then
continue
fi
echo "Number: $i"
if [ $i -eq 4 ]; then
break
fi
done
Output:
Number: 1
Number: 2
Number: 4
The do block contains all logic for the loop body.
Do In One-Liners And Scripts
You can write loops on a single line for quick tasks. This is common in command-line one-liners:
for f in *.txt; do echo "File: $f"; done
In scripts, you spread the loop across multiple lines for clarity:
for f in *.txt
do
echo "Processing $f"
wc -l "$f"
done
Both forms use do to define the action block.
Do With Arithmetic Conditions
Bash supports arithmetic expressions with double parentheses. The do keyword still applies:
for ((i=1; i<=3; i++)); do
echo "Iteration $i"
done
Output:
Iteration 1
Iteration 2
Iteration 3
Here, do follows the arithmetic loop header.
Do In While Read Loops
A common pattern is reading a file line by line:
while IFS= read -r line; do
echo "Line: $line"
done < file.txt
The do keyword starts the block that processes each line. This is efficient for large files.
Do With Multiple Commands
You can include any number of commands inside the do...done block:
for user in alice bob charlie; do
echo "Creating user: $user"
sudo useradd "$user"
echo "User $user created"
done
Each command runs in sequence for every iteration.
Do In Infinite Loops
An infinite loop uses while true; do or while :; do. This runs forever until interrupted:
while true; do
echo "Running..."
sleep 1
done
Press Ctrl+C to stop. The do keyword is crucial for defining the repeating block.
Do With Conditional Exits
You can break an infinite loop with a condition:
count=0
while true; do
((count++))
if [ $count -eq 5 ]; then
break
fi
echo "Count: $count"
done
Output:
Count: 1
Count: 2
Count: 3
Count: 4
The do block contains the break logic.
Do In Functions
You can use loops inside functions. The do keyword works the same:
print_numbers() {
for i in "$@"; do
echo "Number: $i"
done
}
print_numbers 10 20 30
Output:
Number: 10
Number: 20
Number: 30
The do block is scoped within the function.
Do With Arrays
Iterate over array elements:
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
Output:
Fruit: apple
Fruit: banana
Fruit: cherry
The do keyword processes each element.
Do In Case Statements
While case does not use do, it is often combined with loops. For example:
for option in start stop restart; do
case $option in
start) echo "Starting";;
stop) echo "Stopping";;
restart) echo "Restarting";;
esac
done
Here, do wraps the case block.
Do With I/O Redirection
You can redirect output from the entire loop:
for i in 1 2 3; do
echo "Line $i"
done > output.txt
This writes all output to a file. The do block is the source of the redirection.
Do In Pipelines
Loops can be part of a pipeline. For example:
for i in 1 2 3; do
echo "$i"
done | grep 2
Output:
2
The do block feeds data into the pipeline.
Do With Debugging
Use set -x to debug loops. The do keyword is visible in trace output:
set -x
for i in 1 2; do
echo "$i"
done
set +x
You will see each command inside the do block printed before execution.
Do In Bash Vs Other Shells
The do keyword is standard in POSIX shells. It works in bash, sh, zsh, and ksh. However, some older shells may have limitations. Always test your scripts.
Do In Zsh
Zsh uses the same syntax. Example:
for i in 1 2 3; do
echo $i
done
No differences in basic usage.
Do In Scripting Best Practices
Always indent the code inside do...done for readability. Use meaningful variable names. Avoid unnecessary commands inside the loop for performance.
Do With Error Handling
Check for errors inside the loop:
for file in *.txt; do
if [ ! -f "$file" ]; then
echo "Error: $file not found"
continue
fi
echo "Processing $file"
done
The do block handles errors gracefully.
Do In Real-World Scripts
Here is a backup script example:
for dir in /home/*/Documents; do
user=$(basename "$(dirname "$dir")")
tar -czf "/backup/${user}_backup.tar.gz" "$dir"
echo "Backup for $user completed"
done
The do keyword runs the backup commands for each user.
Do With Logging
Log loop activity:
logfile="loop.log"
for i in 1 2 3; do
echo "$(date): Processing $i" >> "$logfile"
sleep 1
done
Each iteration appends to the log file.
Do In Parallel Processing
You can run loops in the background with &:
for i in 1 2 3; do
sleep 1 &
done
wait
This runs all iterations concurrently. The do block contains the background command.
Do With Subshells
Use parentheses to run a loop in a subshell:
(for i in 1 2; do echo "$i"; done)
This isolates variable changes.
Do In Interactive Use
You can type loops directly in the terminal. For example:
for i in {1..5}; do echo "Number $i"; done
This is useful for quick tests.
Do With Command Substitution
Use command output as loop input:
for file in $(ls *.txt); do
echo "Found: $file"
done
Be careful with spaces in filenames. Use while read instead for safety.
Do In Loops With Multiple Variables
Bash allows multiple variables in for loops using arrays:
for i in "${!array[@]}"; do
echo "Index: $i, Value: ${array[$i]}"
done
The do block accesses both index and value.
Do With Associative Arrays
Iterate over key-value pairs:
declare -A colors
colors[red]="#FF0000"
colors[green]="#00FF00"
for key in "${!colors[@]}"; do
echo "$key: ${colors[$key]}"
done
The do keyword processes each key.
Do In Loops With Ranges
Brace expansion creates ranges:
for i in {1..10..2}; do
echo "Odd: $i"
done
Output:
Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9
The do block handles each step.
Do With C-Style Loops
Bash supports C-style for loops:
for ((i=0; i<5; i++)); do
echo "i=$i"
done
Output:
i=0
i=1
i=2
i=3
i=4
The do keyword follows the double parentheses.
Do In Loops With External Commands
Use find with a loop:
find . -name "*.log" -type f | while read file; do
echo "Cleaning $file"
> "$file"
done
Here, do starts the cleanup block.
Do With Awk Or Sed
Combine loops with text processing:
for file in *.csv; do
awk -F, '{print $1}' "$file" >