for command in Linux with Examples
Introduction
The for command in linux used in shell scripting to iterate over a set of values or perform set of tasks repeatedly. The for loop allows users to automate operations efficiently which is easier to maintain.
Syntax:
for NAME [in WORDS ... ] ; do COMMANDS; doneHere NAME takes the value of each item in the list.
WORDS contains a set of values.
COMMANDS contains a set of actions to perform.
Example:
for i in 0 1 2 3 4
do
echo "$i"
doneOutput

Options used with for loop :
option | Description |
|---|---|
for var in * | Iterate through all files in the current directory |
for var in {start..end} | Loop through a sequence of numbers or characters |
for var in $(command) | Iterate through the output of a command |
Iterating over files in a directory :
for file in *; do
echo "$file"
doneOutput

The above image kept for reference. There are so many rows for this output.
Iterating over a range of numbers :
for i in {1..5}; do
echo "Number $i"
doneOutput :

Using command output :
for process in $(ps -e | awk '{print $1}'); do
echo "Process ID: $process"
doneOutput :

The above image kept for reference. There are so many rows for this output.
Options:
- help for : It displays help information.

Conclusion
The for command in linux is essential tool in shell scripting. Whether iterating over files, lists the for loop enhances productivity. Understanding its various forms and applications allow users to write more powerful scripts which can create robust solutions.