← Back to Bash Course | Chapter 6: Arrays | Lesson 8 of 10

Arrays पर Looping

एक array को loop करना एक teacher द्वारा class list से हर student का नाम बुलाने जैसा है, एक बार में एक, जब तक हर किसी की बारी न आ जाए।

In this page:

  1. Looping Arrays
Syntax
bash
for item in "${array_name[@]}"; do
  commands using "$item"
done

Looping Arrays

for item in "${array[@]}" directly एक array की values पर iterate करता है, जो हर element process करने का सबसे idiomatic तरीका है।

Index से loop करना इसके बजाय, for i in "${!array[@]}" के साथ, उपयोगी है जब आपको value के साथ position भी चाहिए। "${array[@]}" को quote करना spaces वाले elements को split होने से रोकता है।

Note:
  • Simple value iteration के लिए for item in "${array[@]}" पसंद करें
  • Index form सिर्फ तब उपयोग करें जब आपको index भी चाहिए।

उदाहरण: Looping Arrays

bash
#!/bin/bash
tasks=("Write code" "Run tests" "Deploy")

for task in "${tasks[@]}"; do
    echo "- $task"
done
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. for i in ${arr[@]} बिना quotes के उपयोग करना, जो spaces वाले items को split करता है।
  2. एक loop में ${arr[*]} उपयोग करना जब आपको हर item अलग-अलग चाहिए।
  3. Array को loop करते हुए change करना।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.