
Bash arrays are zero-indexed: the first element is at index
0, the second at 1, and so on.Why Use Arrays?
- Direct element access reduces loops and conditional checks.
- Cleaner scripts when handling lists of servers, filenames, or configurations.
- Improved performance versus string-based lists requiring manual parsing.
Declaring Arrays
1. Assigning by Index
![The image illustrates an array with three indexed elements (0, 1, 2), highlighting the second element (index 1) as "server[1]".](https://kodekloud.com/kk-media/image/upload/v1752868542/notes-assets/images/Advanced-Bash-Scripting-Arrays/array-indexed-elements-server1.jpg)
2. Inline Initialization
declare -a:
Accessing Array Elements
Get All Elements
Quoting Arrays: Preserve Whitespace
Unquoted expansions split on spaces:Always quote
Unquoted expansions can lead to unexpected word splitting.
${array[@]} in loops or commands to preserve elements containing spaces.Unquoted expansions can lead to unexpected word splitting.
Modifying Arrays
Append an Element
Overwrite Entire Array
Assigning a string replaces index0 but retains the array type: