Project 2
#!/bin/bash
#This is a program to perform a binary search for a given signal
#Check if user has can-utils installed
if ! [ -x "$(command -v candump)" ]; then
echo 'Error: candump is not installed.' >&2
exit 1
fi
#Prompt the user for input
echo "Please enter the name of the signal you want to search for:"
read signal
#Perform the initial search
candump -l -c $signal > searchlog.txt
echo "Initial search log created. Enter 'Y' if the signal was found, 'N' otherwise:"
read response
#Check the response
if [ $response = "Y" ]; then
echo "Signal found!"
exit
elif [ $response = "N" ]; then
echo "Signal not found. Starting binary search..."
fi
#Set up the initial parameters
start=0
end=$(wc -l < searchlog.txt)
found=0
#Begin the binary search
while [ $found -eq 0 ]
do
#Calculate the middle index
middle=$((start + end))
middle=$((middle/2))
#Split the log into two halves
head -$middle searchlog.txt > searchlog_a.txt
tail -$((end-middle)) searchlog.txt > searchlog_b.txt
#Check the first half
echo "Checking first half of the log..."
candump -l -c $signal < searchlog_a.txt > search_result_a.txt
echo "Enter 'Y' if the signal was found in the first half of the log, 'N' otherwise:"
read response_a
#Check the second half
echo "Checking second half of the log..."
candump -l -c $signal < searchlog_b.txt > search_result_b.txt
echo "Enter 'Y' if the signal was found in the second half of the log, 'N' otherwise:"
read response_b
#Check the responses
if [ $response_a = "Y" ]; then
echo "Signal found!"
found=1
elif [ $response_a = "N" ] && [ $response_b = "Y" ]; then
echo "Signal found!"
found=1
elif [ $response_a = "N" ] && [ $response_b = "N" ]; then
echo "Signal not found. Halving the log..."
end=$middle
else
echo "Invalid input. Please try again."
fi
#Display the number of messages remaining
remaining=$((end-start))
echo "$remaining message(s) remaining in the kept log"
done