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


Warning: Undefined array key "socialize_RedditWidget" in /home/phpacd/websites/shkodenko.com/wp-content/plugins/socialize/frontend/socialize-services.php on line 166

Warning: Undefined array key "socialize_LinkedInWidget" in /home/phpacd/websites/shkodenko.com/wp-content/plugins/socialize/frontend/socialize-services.php on line 211

Warning: Undefined array key "socialize_PinterestWidget" in /home/phpacd/websites/shkodenko.com/wp-content/plugins/socialize/frontend/socialize-services.php on line 238

Warning: Undefined array key "socialize_PocketWidget" in /home/phpacd/websites/shkodenko.com/wp-content/plugins/socialize/frontend/socialize-services.php on line 279

Warning: Undefined array key "pocket_counter" in /home/phpacd/websites/shkodenko.com/wp-content/plugins/socialize/frontend/socialize-services.php on line 280

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.