Bash Script for Linear Search with Example and Explanation
for and compares each element using if; for example: for i in "${arr[@]}"; do if [[ "$i" == "$target" ]]; then echo "Found"; fi; done.Examples
How to Think About It
if. If you find it, you stop and report the position; if not, you say it is not found.Algorithm
Code
#!/bin/bash arr=(10 20 30 40 50) target=30 found=-1 for i in "${!arr[@]}"; do if [[ "${arr[i]}" == "$target" ]]; then found=$i break fi done if [[ $found -ge 0 ]]; then echo "Element $target found at index $found" else echo "Element $target not found in the array" fi
Dry Run
Let's trace searching for 30 in the array (10 20 30 40 50).
Check index 0
arr[0]=10, target=30, not equal
Check index 1
arr[1]=20, target=30, not equal
Check index 2
arr[2]=30, target=30, equal, found=2, stop loop
| Index | Array Value | Target | Match? |
|---|---|---|---|
| 0 | 10 | 30 | No |
| 1 | 20 | 30 | No |
| 2 | 30 | 30 | Yes |
Why This Works
Step 1: Loop through array indices
The script uses for i in "${!arr[@]}" to get each index to access array elements.
Step 2: Compare each element with target
Inside the loop, if [[ "${arr[i]}" == "$target" ]] checks if the current element matches the target.
Step 3: Stop when found
If a match is found, found is set to the index and break exits the loop early.
Step 4: Report result
After the loop, the script prints the index if found or a not found message.
Alternative Approaches
#!/bin/bash arr=(10 20 30 40 50) target=30 index=0 found=-1 while [[ $index -lt ${#arr[@]} ]]; do if [[ "${arr[index]}" == "$target" ]]; then found=$index break fi ((index++)) done if [[ $found -ge 0 ]]; then echo "Element $target found at index $found" else echo "Element $target not found in the array" fi
#!/bin/bash arr=(10 20 30 40 50) target=30 index=$(printf "%s\n" "${arr[@]}" | grep -nx "$target" | cut -d: -f1) if [[ -n $index ]]; then echo "Element $target found at index $((index-1))" else echo "Element $target not found in the array" fi
Complexity: O(n) time, O(1) space
Time Complexity
The script checks each element once until it finds the target or finishes the array, so it runs in linear time O(n).
Space Complexity
It uses only a few extra variables and no additional data structures, so space complexity is O(1).
Which Approach is Fastest?
The for-loop approach is simple and efficient; using grep involves spawning external processes, which is slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For-loop with indices | O(n) | O(1) | Simple and efficient linear search |
| While loop with manual index | O(n) | O(1) | Clear index control, similar performance |
| Grep with printf | O(n) | O(n) | Text processing, less efficient, useful for strings |
"${!arr[@]}" to loop over array indices in Bash for easy access.