(a) Title:
Accept a user input to determine if the input can be used as a variable
Conditions that can be used as variables
(1) Uppercase and lowercase letters can be
(2) A number may be in the middle of the letter, but cannot begin with a number
(3) Special characters except "_" can not be used as variables
For example:
[Email protected] hushuai]# bash 22.sh
Input:1dsf
Name is not
[Email protected] hushuai]# bash 22.sh
Input:=ewr
Name is not
[Email protected] hushuai]# bash 22.sh
Input:_
Name is OK
[Email protected] hushuai]# bash 22.sh
Input:_123
Name is OK
[Email protected] hushuai]#
The shell code is as follows:
Version 1:
#!/bin/bash
Read-p "Input:" A
B= ' echo $a | Sed-r ' s/[a-za-z0-9_]/a/g ' |grep-o ' a ' |wc-l '
C=${#a}
D= ' echo $a |cut-c1 '
echo $d | grep ' [0-9] ' &>/dev/null
If [$?-eq 0];then
echo $a is not && exit 0
Fi
If [$c-eq $b];then
echo $a is ok
Else
Echo $a is not
Fi
Version of a replacement after the number of statistics, it is troublesome, we directly replace the empty is not good? Revisions on the basis of version (i)
Version (b)
The shell code is as follows:
#!/bin/bash
Read-p "Input:" A
D= ' echo $a |cut-c1 '
echo $d | grep ' [0-9] ' &>/dev/null
If [$?-eq 0];then
echo $a is not && exit 0
Fi
B= ' echo $a | Sed-r ' s/[a-za-z_0-9]//g '
If [-Z $b];then
echo $a is ok
Else
Echo $a is not
Fi
This is a method because the writing of the regular, so it is relatively simple, in fact, we can also be a letter a letter to compare
Example: Version (c)
The shell code is as follows:
#!/bin/bash
Read-p "Plz Input A Name:" N
s=${#n}
Start= ' echo $n |cut-c1 '
Check= ' echo $start | Grep-c ' [A-za-z_] '
If [$check-ne 1];then
echo "Name not OK" && exit 1
Fi
For i in ' seq 2 $s '
Do
Xxoo= ' echo $n |cut-c $i '
Check= ' echo $xxoo | Grep-c ' [a-za-z_0-9] '
If [$check-ne 1];then
echo "Name not OK" && exit 1
Fi
Done
echo "Name is OK"
All of the above just provides a way of thinking and learning to study more on a problem, in fact, if you know an order, there is another way.
Command: eval
Version (iv):
#!/bin/bash
Read-p "Input:" N
Eval $n =1 &>/dev/null
If [$?-eq 0];then
echo "Name is OK"
Else
echo "Name is not"
Fi
This article from "It Life" blog, declined reprint!
Shell finishing (29) = = = Determines whether the user input can be used as a variable