0

In a bash script I have a function, in which I want to check if the passed argument contains only lowercase letters, numbers and "_":

Also to check not to be only numbers and start only with a letter

The code:

function check_name () {

 if [[ $1 != [a-z0-9\\_]; then
    echo The name can contain only lowercase letters, numbers and _
    return 1
 fi

}

The code fails, because always the condition is true and returns 1

2
  • I checked the answer, I tried, in my case I have negation and used !=~ will give me syntax error, if I try ~= is always true(viceversa) so not solving my problem Commented Sep 15, 2018 at 13:10
  • 'If' line has a syntax error - check the number of closing brackets. Commented Sep 15, 2018 at 13:33

1 Answer 1

1

You can do like this:

[STEP 115] $ var=abc123_
[STEP 116] $ [[ -z ${var//[_[:digit:][:lower:]]} ]] && echo yes || echo no
yes
[STEP 117] $ var=ABC
[STEP 118] $ [[ -z ${var//[_[:digit:][:lower:]]} ]] && echo yes || echo no
no
[STEP 119] $

Or

[STEP 125] $ var=abc123_
[STEP 126] $ [[ $var == +([_[:digit:][:lower:]]) ]] && echo yes || echo no
yes
[STEP 127] $ var=ABC
[STEP 128] $ [[ $var == +([_[:digit:][:lower:]]) ]] && echo yes || echo no
no
[STEP 129] $

Or

[STEP 130] $ var=abc123_
[STEP 131] $ [[ $var =~ ^[_[:digit:][:lower:]]+$ ]] && echo yes || echo no
yes
[STEP 132] $ var=ABC
[STEP 133] $ [[ $var =~ ^[_[:digit:][:lower:]]+$ ]] && echo yes || echo no
no
[STEP 134] $
Sign up to request clarification or add additional context in comments.

8 Comments

thanks, I try to check further && [[ $1 =^[:lower:] ]] (beginning with letters) and fails; what about not contain only numbers
i dont quite understand what you meant. elaborate a bit more?
I want to check not to be only numbers and the first and last character can be only a letter. so it can't be 1233 or '1kjfsfs' or '_fafsa' or ffaa123 or fff_
sounds like a different question. please ask a new question.
2) I'd mention it needs extglob enabled 3) Fails for var=FOOabc123_. Add ^ and $ to your regex.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.