I know there is a way to do it but I can't seem to remember now. I have a small shell script which has a simple while loop and it iterates through a CSV file and has an if else loop inside it. The problem is for every line the while loop iterates the if else statement prints a no match found until it finds a match or it keeps printing no match until end of file is reached. I wanted to check how can I print no-match found only once after iterating through the entire file. Here is my sample code below
while IFS=, read -r path servicename app text1 text2 text3;
do
text1="$key1"
text2="$key2"
text3="$key3"
if [[ $servicename = $SERVICE_NAME ]];
then
if [[ $ENV = "sb" ]]; then
ID="$key1"
elif [[ $ENV = "lb" ]]; then
ID="$key2"
elif [[ $ENV = "dev" ]]; then
ID="$key3"
fi
else
echo "no match found"
fi
done < $input_file
sample data that is used in the iteration
path,service,app,text1,text2,text3
path/of/service1,servicename1,appname,key1,key2,key3
path/of/service2,servicename2,appname,key1,key2,key3
path/of/service3,servicename3,appname,key1,key2,key3
path/of/service4,servicename4,appname,key1,key2,key3
path/of/service5,servicename5,appname,key1,key2,key3
CodePudding user response:
Use a variable that keeps track if a match was found or not, and display the message at the end only.
Like this:
#!/bin/bash
SERVICE_NAME="blablabla"
ENV="blablabla"
input_file="input.txt"
match_found="no"
while IFS=, read -r path servicename app text1 text2 text3
do
text1="$key1"
text2="$key2"
text3="$key3"
if [[ "$servicename" == "$SERVICE_NAME" ]]
then
match_found="yes"
if [[ "$ENV" == "sb" ]]
then
ID="$key1"
elif [[ "$ENV" == "lb" ]]
then
ID="$key2"
elif [[ "$ENV" == "dev" ]]
then
ID="$key3"
fi
fi
done < "$input_file"
if [[ "$match_found" == "no" ]]
then
printf "No match found\n"
fi
Another couple modifications:
- used
==
in the if conditions to check if text matches - all variables use is double quoted
- I had to set a couple global variables to some bogus values to test my answer. When you ask a question, you should provide a complete minimal sample.