Reputation: 41
I was writing a bash script to check whether the first word on each line is equal to a certain value but it isn't returning the expected values.
the bash script
#!/bin/bash
if [ $# != 3 ]; then
echo "Error no file specified, default files will be considered"
a="input.txt"
b="correct.txt"
c="incorrect.txt"
while read -r line; do
d=( $line )
e=${d[0]}
if [ $e != "add" ] || [ $e != "sub" ] || [ $e != "addi" ] || [ $e != "lw" ] || [ $e != "sw" ]
then
echo "error"
else
echo "correct"
fi
done < "$a"
fi
the input.txt file:
ok lol no
right back go
why no right
sub send bye
The actual result is: error error error error
the expected result is: error error error correct
Upvotes: 0
Views: 1858
Reputation: 531315
A case
statement would be clearer.
case $e in
add|sub|addi|lw|sw) echo "correct" ;;
*) echo "error"
esac
Upvotes: 1
Reputation: 1446
try this:
if ! [[ "$e" =~ (add|sub|addi|lw|sw)$ ]];then
complete code:
#!/bin/bash
if [ $# != 3 ]; then
echo "Error no file specified, default files will be considered"
a="input.txt"
b="correct.txt"
c="incorrect.txt"
while read -r line; do
d=( $line )
e=${d[0]}
if ! [[ "$e" =~ (add|sub|addi|lw|sw)$ ]];then
echo "e[$e] - error"
else
echo "e[$e] - correct"
fi
done < "$a"
fi
output:
> ./testInput.bash
Error no file specified, default files will be considered
e[ok] - error
e[right] - error
e[why] - error
e[sub] - correct
Upvotes: 1