Validate user input arguments the legality of the shell script _linux shell

Source: Internet
Author: User
Tags lowercase

Today's example is used to validate the legality of the parameters entered by the user, and the program is not complicated, as follows:

#!/bin/sh
# validalphanum-ensures that input consists only of alphabetical
# and numeric characters.

Validalphanum ()
{
 # Validate Arg:returns 0 if all upper+lower+digits, 1 otherwise

 # Remove all unacceptable C HARs
 compressed= "$ (echo $ | sed-e ' s/[^[:alnum:]]//g ')"

 if ["$compressed"!= "$input"]; then return
  1
  else return
  0
 fi
}

# Sample usage of this function in a script

echo-n "Enter input:"
rea D input

if! validalphanum "$input"; then  #//This is a bit tricky, that is, if the function returns a value of 1, then execute
 echo "Your input must consist of O nly letters and numbers. ">&2
 exit 1
Else
 echo" Input is valid. "
Fi

Exit 0

As mentioned above, the scripting process and the idea is very concise, that is, your input with sed filtered in the original input compared to the input is not equal to the illegal.
Noteworthy places are
1) sed-e ' s/[^ [: alnum:]]//g ' ([: Alnum:] is the meaning of uppercase and lowercase letters and numbers, where the role of SED is to filter out uppercase and lowercase letters and numbers.
2) if! Validalphanum "$input" $input be invoked as a parameter to the function, note that quotes are added here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.