-3

Which operator should be used between ~ and ! while checking a regular expression in IF condition in shell scripting??

Will there be any difference between the two cases shared below ??

case 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

case 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
2
  • 4
    For a homework question like this it wouldn't have been terribly hard to try the two options yourself. Commented Jan 5, 2017 at 13:25
  • 4
    Please do some research before asking here. While we welcome basic questions, this is something that would have been trivial to find if you'd even spent a few seconds searching. Would you go to a mathematics forum and ask "Is there any difference between + and -?" Commented Jan 5, 2017 at 13:31

1 Answer 1

4

Comparing != and =~ is like comparing apples to oranges.

!= roughly means "not equal", while =~ means "matches". You can read more about this operators under [[ expression ]] in man bash. Here's an excerpt of the most relevant sections:

      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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.