Check if a variable exists in a list in Bash

后端 未结 17 512
囚心锁ツ
囚心锁ツ 2020-11-29 17:08

I am trying to write a script in bash that check the validity of a user input.
I want to match the input (say variable x) to a list of valid values.

<
17条回答
  •  一生所求
    2020-11-29 17:48

    The shell built-in compgen can help here. It can take a list with the -W flag and return any of the potential matches it finds.

    # My list can contain spaces so I want to set the internal
    # file separator to newline to preserve the original strings.
    IFS=$'\n'
    
    # Create a list of acceptable strings.
    accept=( 'foo' 'bar' 'foo bar' )
    
    # The string we will check
    word='foo'
    
    # compgen will return a list of possible matches of the 
    # variable 'word' with the best match being first.
    compgen -W "${accept[*]}" "$word"
    
    # Returns:
    # foo
    # foo bar
    

    We can write a function to test if a string equals the best match of acceptable strings. This allows you to return a 0 or 1 for a pass or fail respectively.

    function validate {
      local IFS=$'\n'
      local accept=( 'foo' 'bar' 'foo bar' )
      if [ "$1" == "$(compgen -W "${accept[*]}" "$1" | head -1)" ] ; then
        return 0
      else
        return 1
      fi
    }
    

    Now you can write very clean tests to validate if a string is acceptable.

    validate "blah" || echo unacceptable
    
    if validate "foo" ; then
      echo acceptable
    else 
      echo unacceptable
    fi
    

提交回复
热议问题