I would like to check hostnames to make sure they follow the standard naming convention in Bash Shell
.
Let say the hostname is ab-cde-01
wolf@linux:~$ h='ab-cde-01'
wolf@linux:~$ echo $h
ab-cde-01
wolf@linux:~$
I started by building if else loop and it's working just fine.
wolf@linux:~$ if [ $h = 'ab-cde-01' ]; then
> echo $h is a valid name
> else
> echo $h is an INVALID name
> fi
ab-cde-01 is a valid name
wolf@linux:~$
However, when I try to use regex to replace numbers with [0-9], I'm getting an invalid name.
wolf@linux:~$ if [ $h = 'ab-cde-0[0-9]' ]; then
> echo $h is a valid name
> else
> echo $h is an INVALID name
> fi
ab-cde-01 is an INVALID name
wolf@linux:~$
update 1: =~ operator
=~
operator used as suggested ...
wolf@linux:~$ if [ $h =~ 'ab-cde-0[0-9]' ]; then
> echo $h is a valid name
> else
> echo $h is an INVALID name
> fi
bash: [: =~: binary operator expected
ab-cde-01 is an INVALID name
wolf@linux:~$
update 2: double bracket
wolf@linux:~$ if [[ $h =~ 'ab-cde-0[0-9]' ]]; then
> echo $h is a valid name
> else
> echo $h is an INVALID name
> fi
ab-cde-01 is an INVALID name
wolf@linux:~$
- What's wrong in this code?
- How to fix it?
- Is this the right/most efficient way to check hostname against certain standard?
update 3: Actual answer for my own reference too
wolf@linux:~$ if [[ $h =~ ab-cde-0[0-9] ]]; then
> echo $h is a valid name
> else
> echo $h is an INVALID name
> fi
ab-cde-01 is a valid name
wolf@linux:~$
Lessons learned
- Use double bracket instead of single bracket
- No quote in regex
Bash Shell
. Question updated – Wolf Jul 09 '20 at 10:25=~
operator produces an error in the code.
– Wolf Jul 09 '20 at 10:26bash: [: =~: binary operator expected
[[ ... ]]
double bracket test operator. – AdminBee Jul 09 '20 at 10:26