List पर for Loop
In this page:
for variable in item1 item2 item3; do
commands using "$variable"
done
for variable in {start..end}; do
commands
done
Basic for...in Loop
Classic for var in list; do ... done form एक space-separated list of words के ऊपर iterate करता है, हर एक को बारी-बारी var में assign करते हुए body के उपयोग के लिए। List directly literal words के रूप में लिखी जा सकती है।
उदाहरण: Basic for...in Loop
#!/bin/bash
for color in red green blue; do
echo "Color: $color"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over a Variable's Words
कई space-separated words रखने वाला एक variable सीधे in list में unquoted छोड़कर loop किया जा सकता है, क्योंकि Bash इसे अलग-अलग items में word-split करता है।
यह convenient है, लेकिन सिर्फ तब safe है जब आप जानते हों कि values में meaningful embedded spaces नहीं हैं।
उदाहरण: Looping Over a Variable's Words
#!/bin/bash
names="ada grace linus"
for n in $names; do
echo "Hello, $n"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over a Numeric Range with Brace Expansion
{start..end} brace expansion numbers (या letters) की एक sequence generate करता है बिना seq जैसी external command की ज़रूरत के। यह loop शुरू होने से पहले ही Bash द्वारा evaluate होता है, literal words की एक plain list produce करते हुए।
उदाहरण: Looping Over a Numeric Range with Brace Expansion
#!/bin/bash
for i in {1..5}; do
echo "Iteration $i"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over Command Substitution Output
in के बाद वाली list एक command substitution से भी आ सकती है, आपको dynamically generated data जैसे filenames या lines of output के ऊपर iterate करने देते हुए।
चूंकि word splitting अब भी apply होती है, यह सबसे अच्छा तब काम करता है जब values में embedded spaces न होने की गारंटी हो।
उदाहरण: Looping Over Command Substitution Output
#!/bin/bash
for word in $(echo "one two three"); do
echo "Got word: $word"
done
Login to try C/C++/Java/PHP code in the editor
- एक variable से list बनाते समय spaces वाले list items को quote करना भूल जाना, जिससे loop whitespace पर split होकर इरादे से ज़्यादा items के ऊपर iterate करता है।
- यह मान लेना कि
for x in listको items के बीच commas चाहिए; Bash for-loops list items को whitespace से separate करते हैं, commas से नहीं। - Simple numeric ranges के लिए habit से
for i in $(seq 1 $n)उपयोग करना जब Bash की अपनी brace expansion ({1..n}) या C-style for loop simpler है और एक extra process spawn करने से बचाता है।
- Syntax:
for var in item1 item2 item3; do ... done--varबारी-बारी हर value लेता है। - List literal words, एक variable expansion, command substitution, या
{1..5}जैसी brace expansion से आ सकती है। - Quoting मायने रखती है:
for f in $unquoted_listword-splits करता है, जबकिfor f in "${array[@]}"हर array element को intact रखता है। - Loop body list में items के appear होने के order में, हर item के लिए एक बार चलती है।
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: