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

user3541631
  • 3,686
  • 8
  • 48
  • 115
  • 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 – user3541631 Sep 15 '18 at 13:10
  • 'If' line has a syntax error - check the number of closing brackets. – Dejan D. Sep 15 '18 at 13:33

1 Answers1

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] $
pynexj
  • 19,215
  • 5
  • 38
  • 56
  • thanks, I try to check further && [[ $1 =^[:lower:] ]] (beginning with letters) and fails; what about not contain only numbers – user3541631 Sep 15 '18 at 13:54
  • i dont quite understand what you meant. elaborate a bit more? – pynexj Sep 15 '18 at 14:13
  • 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_ – user3541631 Sep 15 '18 at 14:50
  • sounds like a different question. please ask a new question. – pynexj Sep 15 '18 at 14:53
  • 2) I'd mention it needs `extglob` enabled 3) Fails for `var=FOOabc123_`. Add `^` and `$` to your regex. – PesaThe Sep 15 '18 at 15:37
  • i remember `extglob` is implicitly enabled for `==`. will double check later. (regex fixed. thanks.) – pynexj Sep 15 '18 at 15:44
  • @pynexj `shopt -s extglob` is solely for compatibility reasons. Read this [comment](https://stackoverflow.com/questions/50220152/bash-script-accept-integer-only-if-is-from-range/50220536#comment87459599_50220536). – PesaThe Sep 15 '18 at 15:54
  • You may also go for something like `[[ $var = *[^_[:digit:][:lower:]]* ]]` to detect invalid input instead. – PesaThe Sep 15 '18 at 16:07