Exploring Array Syntax in Shell Scripting: A C-Like Approach

Shell scripting provides a versatile way to automate tasks in Unix-like systems. For programmers familiar with C or languages with similar syntax, the following pattern can be particularly intuitive:

#!/usr/bin/env sh

arr=('foo' 'bar' 'baz')

for ((i=0; i < ${#arr[@]}; i++)); do
    echo "arr[${i}]: ${arr[i]}"
done

In this script, we define an array named arr with three string elements: ‘foo’, ‘bar’, and ‘baz’. We then iterate over the array using a for loop that closely resembles the syntax in C.

The loop utilizes a C-style for-loop syntax to iterate over the array indices. With i as the index, the loop runs as long as i is less than the length of the array, which we obtain with ${#arr[@]}. Within the loop, each element of the array is accessed via ${arr[i]} and printed out alongside its index.

This syntax provides a familiar structure for those accustomed to C-like languages, offering a seamless transition to writing shell scripts.