regexbashcase-insensitive

Case insensitive regex in Bash


I want to know which method is better to check if a var (input by user on keyboard) matches with a regex in a case insensitive way. I know there are some different possibilities. Example: I want a regex matching an empty value and all of this list: Y, N, y, n, Yes, No, YES, NO

I searched looking different methods. Not sure if could be another better. I'll put a couple of them working for me.

Can these regex get improved in any way? Is there a better (more elegant) method? On second method, is there a way to revert that setting?


Solution

  • shopt is good approach as you are able to retain originally entered value in variable yesno.

    You can just refactor your regex a bit:

    #!/bin/bash
    
    yesno="null"
    
    # set nocasematch option
    shopt -s nocasematch
    
    while [[ ! ${yesno} =~ ^([yn]|yes|no)?$ ]]; do
        read -r -p "Enter a yes/no value: " yesno
    done
    
    # unset nocasematch option
    shopt -u nocasematch
    
    # examine your variable
    declare -p yesno