~ 和 ! 之间的区别在unix shell脚本中

~ 和 ! 之间的区别在unix shell脚本中

~ 和 ! 之间应使用哪个运算符在 shell 脚本中检查 IF 条件中的正则表达式时?

下面分享的两个案例有什么区别吗?

情况1:

if [[ $file_date != ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; 
then    
    echo -e "The file_date is not in the required format"; 
else
    echo "doing good";
fi

案例2:

if [[ $file_date =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; 
then    
    echo -e "The file_date is not in the required format"; 
else
    echo "doing good";
fi

答案1

比较!==~就像比较苹果和橘子一样。

!=粗略的意思是“不等于”,而=~意思是“匹配”。您可以[[ expression ]]在 中阅读有关此运算符的更多信息man bash。以下是最相关部分的摘录:

      When the == and != operators are used, the string to the  right  of
      the  operator  is considered a pattern and matched according to the
      rules described below under Pattern Matching,  as  if  the  extglob
      shell option were enabled.  The = operator is equivalent to ==.  If
      the shell option nocasematch is enabled,  the  match  is  performed
      without  regard  to  the case of alphabetic characters.  The return
      value is 0 if the string matches (==) or does not  match  (!=)  the
      pattern, and 1 otherwise.  Any part of the pattern may be quoted to
      force the quoted portion to be matched as a string.

      An additional binary operator, =~,  is  available,  with  the  same
      precedence  as == and !=.  When it is used, the string to the right
      of the operator is considered an extended  regular  expression  and
      matched accordingly (as in regex(3)).  The return value is 0 if the
      string matches the  pattern,  and  1  otherwise.   If  the  regular
      expression is syntactically incorrect, the conditional expression's
      return value is 2.

相关内容