Array Iteration in Shell
Level 4188 keystrokes
Loops over an indexed array by index with ${!servers[@]}, prints a slice with ${servers[@]:1:2}, and replaces "web" with "app" in every element with ${servers[@]/web/app}.
Shell code
# An indexed array with three elements (indices 0-2)1servers=("web1" "web2" "db1")# ${!servers[@]} expands to the indices 0 1 22for i in "${!servers[@]}"; do # Print each index and the element at that index3 echo "[$i] ${servers[$i]}"4done# :1:2 takes 2 elements starting at index 1 -> web2 db15echo "Slice: ${servers[@]:1:2}"# Replace the first "web" in each element with "app" and rebuild the array6servers=("${servers[@]/web/app}")# Prints app1 app2 db17echo "Replaced: ${servers[@]}"Output
[0] web1 [1] web2 [2] db1 Slice: web2 db1 Replaced: app1 app2 db1
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Shell code and how often they appear.
"× 16$× 7[× 6]× 6{× 5}× 5:× 4@× 4(× 2)× 2