0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script for Linear Search with Example and Explanation

Use a Bash script that loops through an array with for and compares each element using if; for example: for i in "${arr[@]}"; do if [[ "$i" == "$target" ]]; then echo "Found"; fi; done.
📋

Examples

Inputarr=(1 2 3 4 5), target=3
OutputElement 3 found at index 2
Inputarr=(apple banana cherry), target=banana
OutputElement banana found at index 1
Inputarr=(10 20 30), target=40
OutputElement 40 not found in the array
🧠

How to Think About It

To do a linear search in Bash, think of checking each item in a list one by one until you find the target or reach the end. You compare each element with the target using if. If you find it, you stop and report the position; if not, you say it is not found.
📐

Algorithm

1
Get the array and the target value.
2
Start from the first element and check if it matches the target.
3
If it matches, return the index and stop.
4
If not, move to the next element.
5
If you reach the end without a match, report not found.
💻

Code

bash
#!/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
Output
Element 30 found at index 2
🔍

Dry Run

Let's trace searching for 30 in the array (10 20 30 40 50).

1

Check index 0

arr[0]=10, target=30, not equal

2

Check index 1

arr[1]=20, target=30, not equal

3

Check index 2

arr[2]=30, target=30, equal, found=2, stop loop

IndexArray ValueTargetMatch?
01030No
12030No
23030Yes
💡

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

Using while loop with index
bash
#!/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
Uses a while loop and manual index increment; slightly more verbose but clear control over index.
Using grep with printf
bash
#!/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
Uses external grep command to find line number; less efficient but shows text processing approach.

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.

ApproachTimeSpaceBest For
For-loop with indicesO(n)O(1)Simple and efficient linear search
While loop with manual indexO(n)O(1)Clear index control, similar performance
Grep with printfO(n)O(n)Text processing, less efficient, useful for strings
💡
Use "${!arr[@]}" to loop over array indices in Bash for easy access.
⚠️
Forgetting to use quotes around variables can cause errors with spaces or special characters.