3 ways to judge variables as numbers in a shell script _linux shell

Source: Internet
Author: User

Method 1: Add a variable to an integer value by using expr, or an integer if it is performed correctly, or an error is executed, $? will be a value that is non 0

Copy Code code as follows:

Expr $args + 0 &>/dev/null

Method 2: Print variables replaced by SED in the way that the number in the variable is NULL, if the variable is empty after the substitution, then integer

Copy Code code as follows:

echo $args | Sed ' s/[0-9]//g '

If you judge a negative number, then filter the minus with SED.

Copy Code code as follows:

echo $args | Sed ' s/[0-9]//g ' | Sed ' s/-//g '

The following script uses two functions to achieve numerical judgment. The code is simple, without comment.

Copy Code code as follows:

#!/bin/bash
Usage () {
Cat <<eof
Useage:sh $0ARGS1 ARGS2
Exit 1
Eof
}
Checkint () {
Expr $1+ 0&>/dev/null
[$-ne 0] && {echo "Args must be integer!"; Exit 1; }
}
CheckInt1 () {
Tmp= ' echo $1|sed ' s/[0-9]//g '
[-N ' ${tmp} ']&& {echo ' Args must be integer! '; Exit 1; }
}
[$#-ne 2]&&usage
Args1=$1
Args2=$2
Checkint $args 1
CheckInt1 $args 2
if[$args 1-gt $args 2];then
echo "Yes, $args 1 greate than $args 2"
Else
echo "No, $args 1 less than $args 2"
Fi

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.