Looping through array values is the common task in Bash scripting. For example, you might want to loop through an array of filenames and execute certain commands on each one.
The Bash scripts provides one dimensional array variables. Any variable may be used as an array; the declare builtin will explicitly declare an array. There is no limit on the size of an array, even no requirement, that members be indexed or assigned contiguously. Arrays are zero-base and are indexed using integers. In this article we will discuss bash scripts and how to use different Bash scripts techniques.
About Bash Scripts
Bash scripts, or shell scripts, are sequences of commands written in the Bash (Bourne Again Shell) scripting language. Bash is a popular Unix shell, a command processor that typically runs in a text window where the user types commands that cause actions.
Bash scripts allow users to automate tasks and execute multiple commands sequentially. They are particularly useful for automating repetitive tasks, managing system configurations, and creating simple programs. Like any other executable file, Bash scripts can have permissions set to control who can execute them.
Here’s a simple example of a Bash script:
#!/bin/bash # This is a comment echo "Hello, world!" # Define variables name="Alice" age=30 # Print variables echo "Name: $name" echo "Age: $age" # Using if statement if [ $age -age 18 ]; then echo "$name is an adult." else echo "$name is a minor." fi
In this script:
– `#!/bin/bash` is the shebang line, indicating that the script should be executed using the Bash interpreter.
– Comments start with `#`.
– `echo` is used to print messages to the terminal.
– Variables `$name` and `$age` store data.
– An `if` statement checks the value of `$age` and prints a message accordingly.
To execute the script, save it to a file (e.g., `example.sh`), make it executable (`chmod +x example.sh`), and run it (`./example.sh`).
Bash scripts are versatile and can be used for a wide range of tasks, from simple system administration tasks to complex automation workflows.
Some Techniques to Write Bash Scripts
Writing Bash scripts to loop through array values is a fundamental skill for any Bash programmer. Bash provides several ways to iterate through array elements efficiently. Let’s explore some techniques.
1. Using a For Loop:
#!/bin/bash # Define an array fruits=("apple" "banana" "orange" "grape") # Loop through array elements using a for loop for fruit in "${fruits[@]}" do echo "Fruit: $fruit" done
In this script:
`for fruit in “${fruits[@]}”` iterates over each element of the array `fruits`.
`“${fruits[@]}”` expands to all elements of the array.
2. Using C-style For Loop:
#!/bin/bash fruits=("apple" "banana" "orange" "grape") # Get the length of the array len=${#fruits[@]} # Loop through array elements using a C-style for loop for ((i = 0; i < len; i++)) do echo "Fruit: ${fruits[i]}" done
Here:
`${#fruits[@]}` gets the length of the array.
The loop iterates from 0 to length-1, accessing each element using `${fruits[i]}`.
3. Using While Loop:
#!/bin/bash fruits=("apple" "banana" "orange" "grape") # Initialize index index=0 # Loop through array elements using a while loop while [ $index -lt ${#fruits[@]} ] do echo "Fruit: ${fruits[index]}" ((index++)) done
Explanation:
The loop continues as long as the index is less than the length of the array `${#fruits[@]}`.
`${fruits[index]}` accesses each element of the array.
4. Looping with Indexed Array:
#!/bin/bash fruits[0]="apple" fruits[1]="banana" fruits[2]="orange" fruits[3]="grape" # Loop through indexed array for index in "${!fruits[@]}" do echo "Index: $index, Fruit: ${fruits[index]}" done
In this example:
`”${!fruits[@]}”` expands to the indices of the array.
`${fruits[index]}` accesses the element corresponding to each index.
5. Looping with Associative Array:
#!/bin/bash # Declare an associative array declare -A colors colors["apple"]="red" colors["banana"]="yellow" colors["orange"]="orange" colors["grape"]="purple" # Loop through associative array for key in "${!colors[@]}" do echo "Fruit: $key, Color: ${colors[$key]}" done
Here:
`declare -A` declares an associative array.
`“${!colors[@]}”` expands to the keys of the associative array.
`${colors[$key]}` accesses the value corresponding to each key.
Conclusion
Bash scripts are useful for creating automated command line behavior, and arrays are a great tool that you can use to store multiple pieces of data.
Declaring and using them is not hard, but it is different from other languages, so pay close attention to avoid making mistakes.