bash运算符不正确的运算符不相等

时间:2019-03-27 10:34:14

标签: linux bash shell

我正在编写一个bash脚本,以检查每行中的第一个单词是否 等于某个值,但未返回期望值。

bash脚本

#!/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

input.txt文件:

ok lol no
right back go
why no right
sub send bye

实际结果是: 错误 错误 错误 错误

预期结果是: 错误 错误 错误 正确

2 个答案:

答案 0 :(得分:1)

尝试:

if ! [[ "$e" =~ (add|sub|addi|lw|sw)$ ]];then

完整代码:

#!/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

输出:

> ./testInput.bash 
Error no file specified, default files will be considered
e[ok] - error
e[right] - error
e[why] - error
e[sub] - correct

答案 1 :(得分:1)

case语句会更清楚。

case $e in
  add|sub|addi|lw|sw) echo "correct" ;;
  *) echo "error"
esac