How can I use a variable that has the conditions for the if statement stored in it?
my test script
condition="[ a = b ] || [ a = a ] || [ c = a ]"
if "$condition"
then echo "true"
else echo "false"
fi
output
$ ./test2.sh
./test2.sh: line 3: [ a = b ] || [ a = a ] || [ c = a ]: command not found
false
Use the eval command and build the condition string as:
condition="[ $a = $b -o $a = $a -o $c = $a ]"
if eval "$condition"
then
echo "true"
else
echo "false"
fi
Thank You, Franklin52.
Adding eval after the if did the trick. I added it on line 28 of the test script below.
my final test script
#!/bin/bash
#test.sh
fileType=( avi flv iso mkv mp4 mpeg mpg wmv )
if [ -n "$1" ]
then
inputFileName="$1"
echo "\$1 = $1"
echo "inputFileName = $inputFileName"
else
for inputFileName in *
do
if [ -f "$inputFileName" ]
then
echo -e "\ninputFileName = $inputFileName"
fileNameExt=`echo $inputFileName|sed 's/.*\.//'`
predicate="[ \"$fileType\" = \"$fileNameExt\" ]"
if [ ${#fileType[@]} != 0 ]
then
i="1"
while [ $i -lt ${#fileType[@]} ]
do
predicateN=""
predicateN=`echo -e "$predicateN|| [ \"${fileType}\" = \"$fileNameExt\" ]"`
predicate="$predicate $predicateN"
i=$[$i+1]
done
fi
if eval "$predicate"
then
echo "yes, $inputFileName has a usable file extension."
fi
fi
done
fi
exit
sample output
$ ./test.sh
inputFileName = bill.mkv
yes, bill.mkv has a usable file extension.
inputFileName = bob.mkv
yes, bob.mkv has a usable file extension.
inputFileName = examples.desktop