I'm trying to write a simple script that validates whether or not multiple variables exist in a file.
The idea is that if the $var1
exists, continue to $var2
. That part is easy, what I'm stuck at is the notion of making it continue even if $var1 isn't there. I'm passing that to another* .txt*.
I have $var1
to $var6
. Each one represents a word, either the word exists or not it should alert. And, if the word exists, it should do another task.
This is what I have right now:
if cat feed.txt | grep "$var1\|$var2\|$var3\|$var4\|$var5\|$var6" > list
This worked fine, but now I need to independently validate them. So I did this
if cat feed.txt | grep "$var1" > list
then
cat feed.txt | grep $var2 >> list
This worked too. But if $var1 isn't there, $var2 is overlooked. And I have 6 variables.
I've been looking at forums where IF, ELIF, ELSE; THEN
operands are explain, but I'm struggling with the logic of all this.
If the checks are independent, use a loop.
#!/bin/bash
vars=( "$var1" "$var2" "$var3" ) # etc etc for additional vars...
for var in "${vars[@]}" ; do
if grep "$var" feed.txt >> list ; then
# found this variable - do something about it
echo "Found $var"
else
# did not find this variable - do something else
echo "Did not find $var"
fi
done