How can I guarantee that a Bash string is alphanumeric, without underscores?

I am adding a function to an existing script that will allow the user to configure the hostname of the Linux system. The rules that I follow are as follows:

  • Must be between 2 and 63 characters
  • Do not start or end with a hyphen
  • May contain only alphanumeric characters and hyphens; all other characters are invalid (including the underscore, which means that I cannot use the \ W regex character)

I solved the first two in the list, but it's hard for me to figure out how to check if the bash string contains only letters, numbers, and hyphens. I think I can do this with a regular expression, but it's hard for me to figure out how (I spent the last hour on the Internet and read the manual pages).

I am open to using sed, grep or any other standard tools, but not Perl or Python.

+6
bash regex grep sed
source share
4 answers

Seems like this should do this:

^[a-zA-Z0-9][-a-zA-Z0-9]{0,61}[a-zA-Z0-9]$ 

Matches any alphanumeric character, and then matches 61 alphanumeric characters (including hyphens), and then matches any alphanumeric character. The minimum line length is 2, the maximum is 63. It does not work with Unicode. If you need to work with Unicode, you need to add different character classes instead of a-zA-Z0-9 , but the principle will be the same.

I believe that the correct grep expression will work with Unicode:

 ^[[:alnum:]][-[:alnum:]]{0,61}[[:alnum:]]$ 
+14
source share

This is a bash script that checks the first parameter, whether it contains only alphanumeric or hyphens. It "passes" the contents of $ 1 to grep:

 #!/bin/bash if grep '^[-0-9a-zA-Z]*$' <<<$1 ; then echo ok; else echo ko; fi 
+2
source share

This is for the last one you need: sed -e 's/[^[:alnum:]|-]//g'

+1
source share

you can only do this with bash

 string="-sdfsf" length=${#string} if [ $length -lt 2 -o $length -gt 63 ] ;then echo "length invalid" exit fi case $string in -* ) echo "not ok : start with hyphen";exit ;; *- ) echo "not ok : end with hyphen";exit ;; *[^a-zA-Z0-9-]* ) echo "not ok : special character";exit;; esac 
0
source share

All Articles