samedi 1 avril 2017

Regular expressions don't work as expected in bash if-else block's condition

My pattern defined to match in if-else block is :

pat="17[0-1][0-9][0-9][0-9].AUG"
nln=""

In my script, I'm taking user input which needs to be matched against the pattern, which if doesn't match, appropriate error messages are to be shown. Pretty simple, but giving me a hard time though. My code block from the script is this:

echo "How many days' AUDIT Logs need to be searched?"
read days
echo "Enter file name(s)[For multiple files, one file per line]: "
for(( c = 0 ; c < $days ; c++))
do
  read elements
  if [[  $elements =~ $pat ]];
     then
       array[$c]="$elements"
  elif [[  $elements =~ $nln ]];
     then
        echo "No file entered.Run script again. Exiting"
        exit;
  else
      echo "Invalid filename entered: $elements.Run script again. Exiting"
      exit;
  fi
done

The format I want from the user for filenames to be entered is this:

170402.AUG

So basically yymmdd.AUG (where y-year,m-month,d-day), with trailing or leading spaces is fine. Anything other than that should throw "Invalid filename entered: $elements.Run script again. Exiting" message. Also I want to check if if it is a blank line with a "Enter" hit, it should give an error saying "No file entered.Run script again. Exiting"

However my code, even if I enter something like "xxx" as filename, which should be throwing "Invalid filename entered: $elements.Run script again. Exiting", is actually checking true against a blank line, and throwing "No file entered.Run script again. Exiting"

Need some help with handling the regular expressions' check with user input, as otherwise rest of my script works just fine.

Aucun commentaire:

Enregistrer un commentaire