← 返回命令列表

Linux command

for 命令

文本

涉及管道、覆盖或删除,执行前请先确认路径和参数。

常用示例

Iterate over list

for item in [a b c]; do echo $item; done

Loop over files

for file in *.txt; do cat "$file"; done

C-style loop

for ((i=0; i<10; i++)); do echo $i; done

Loop with range

for i in {1..10}; do echo $i; done

Process command output

for line in $(cat [file.txt]); do echo "$line"; done

说明

for is a shell keyword that iterates over a list of items, executing commands for each. It's one of the fundamental loop constructs in shell scripting. The loop variable takes each value from the word list in turn. Brace expansion, command substitution, and globbing can generate the list. C-style syntax provides numeric iteration. for loops are essential for batch processing files, generating sequences, and iterating over arrays.

参数

in
Introduces the list of items.
do
Begins the command block.
done
Ends the for loop.

FAQ

What is the for command used for?

for is a shell keyword that iterates over a list of items, executing commands for each. It's one of the fundamental loop constructs in shell scripting. The loop variable takes each value from the word list in turn. Brace expansion, command substitution, and globbing can generate the list. C-style syntax provides numeric iteration. for loops are essential for batch processing files, generating sequences, and iterating over arrays.

How do I run a basic for example?

Run `for item in [a b c]; do echo $item; done` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

What does in do in for?

Introduces the list of items.