Array Basics
An array is like an egg carton: one container with numbered slots, each holding its own item. You pick an item by saying which slot you want, starting at zero.
In this page:
Syntax
array_name=(value1 value2 value3)
echo "${array_name[0]}"
Array Basics
Bash arrays store multiple values in a single variable, declared with name=(value1 value2 value3). Individual elements are accessed with ${name[index]}, using zero-based indexing.
Arrays are one of the few compound data structures Bash offers natively.
Note:
Always quote array expansions, like
"${arr[@]}", to keep elements with spaces intact.Example: Array Basics
#!/bin/bash
fruits=("apple" "banana" "cherry")
echo "First fruit: ${fruits[0]}"
echo "Second fruit: ${fruits[1]}"
Login to try C/C++/Java/PHP code in the editor
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. #}
Common Mistakes
- Writing
arr = (a b c)with spaces, which is a syntax error. - Using
$arrand expecting all items, when it gives only the first; use"${arr[@]}". - Assuming arrays exist in plain
sh, when they are a Bash feature.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: