2013年4月10日 星期三

bash "=~" operator


簡單來說,我們在bash script中的fi statement想加入regular expression時,則可以利用"=~"這個binary operator以及"[["、"]]"來撰寫。例如:

Syntax:   if [[  =~ regex ]]

if  [[ ${var} =~ "eth[0-9]" ]]; then
        # do something....
fi


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 regex3))


Return Value

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



Examples
 # primary parameter checking
    if [[ ! ${dev} =~ eth[0-9] ]]; then
        echo "Error: parameter 'dev' format is not correct: ${dev}"
        exit 1
    elif [[ ! ${vlan} =~ "-*[0-9]" ]]; then
        echo "Error: parameter 'vlan' format is not correct: ${vlan}"
        exit 1
    elif [ -z ${netname} ]; then
        echo "Error: parameter 'netname' format is not correct: ${netname}"
        exit 1
    fi


Reference
[1] http://www.gnu.org/software/bash/manual/bashref.html
[2] http://stackoverflow.com/questions/2348379/use-regular-expression-in-if-condition-in-bash

沒有留言:

張貼留言