C-Style for Loop का उपयोग
for (( init; condition; update )); do
commands
done
Basic C-Style for Loop
तीन sections -- initialization, condition, update -- double parentheses के अंदर semicolons से separate होते हैं, और हर एक एक normal arithmetic expression है। Loop body तब तक चलता है जब तक condition non-zero (true) evaluate हो।
उदाहरण: Basic C-Style for Loop
#!/bin/bash
for (( i = 0; i < 5; i++ )); do
echo "i is $i"
done
Login to try C/C++/Java/PHP code in the editor
Custom Step Sizes
चूंकि update section एक पूरा arithmetic expression है, आप सिर्फ 1 नहीं, बल्कि किसी भी amount से increment कर सकते हैं -- उदाहरण के लिए दो-दो count करने के लिए i += 2, या downward count के लिए i--।
यह flexibility simpler for...in {1..n} form पर main advantage है।
उदाहरण: Custom Step Sizes
#!/bin/bash
for (( i = 0; i <= 10; i += 2 )); do
echo "Even number: $i"
done
Login to try C/C++/Java/PHP code in the editor
Counting Down
C-style loop reverse में भी बिल्कुल naturally काम करता है, एक high value से शुरू करके, > या >= condition उपयोग करके, और update section में decrement करके। यह countdowns या reverse order में कुछ process करने के लिए एक आम pattern है।
उदाहरण: Counting Down
#!/bin/bash
for (( i = 5; i >= 1; i-- )); do
echo "Countdown: $i"
done
echo "Liftoff!"
Login to try C/C++/Java/PHP code in the editor
Omitting Sections
तीनों में से कोई भी section empty छोड़ा जा सकता है; सभी तीनों empty छोड़ना, for (( ; ; )), एक infinite loop produce करता है, जो सिर्फ तब safe है जब body के अंदर किसी और condition के आधार पर एक break के साथ pair किया जाए।
यह pattern आम है जब exit condition को loop body के अंदर एक check के रूप में express करना आसान हो।
उदाहरण: Omitting Sections
#!/bin/bash
count=0
for (( ; ; )); do
echo "count=$count"
count=$((count + 1))
if [ "$count" -ge 3 ]; then
break
fi
done
Login to try C/C++/Java/PHP code in the editor
- तीन sections के बीच semicolons भूल जाना; syntax को strictly
(( init; condition; update ))चाहिए दो semicolons के साथ, commas या newlines नहीं। - यह confuse कर देना कि कौन सा section कौन सा है -- middle section *continue* condition है (loop तब तक चलता रहता है जब तक यह true हो), एक stop condition नहीं।
- Double parentheses के अंदर counter के लिए string values या
$prefixes उपयोग करने की कोशिश करना;(( ))के अंदर आप bare variable names लिखते हैं और यह implicitly numeric है।
- Syntax:
for (( init; condition; update )); do ... done, directly C के for loop पर modeled। - तीनों sections optional हैं -- सिर्फ
for (( ; ; ))एक infinite loop बनाता है, जिसका मतलब है एक internalbreakके साथ pair करना। (( ))के अंदर, variables को बिना leading$के reference किया जाता है, और यह पूरी तरह++,--,+=, आदि support करता है।- यह form ideal है जब आपको एक specific step size (सिर्फ 1 नहीं) या comparison पर आधारित एक stop condition वाला numeric counter चाहिए, सिर्फ एक fixed list नहीं।
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: