简体   繁体   English

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

[英]Not equal operator for bash not working correctly

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. 我正在编写一个bash脚本,以检查每行上的第一个单词是否等于某个值,但是它没有返回预期值。

the bash script 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

the input.txt file: input.txt文件:

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 预期的结果是:错误错误错误正确

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

A case statement would be clearer. case陈述会更清楚。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM