N methods for shell to determine a variable as a number

Source: Internet
Author: User
Method 1: Use expr to calculate the sum of the variable and an integer. If normal execution is performed, the variable is an integer. Otherwise, an error occurs. $? Replace a non-0 value expr $ args + 0 & amp; & gt;/dev/null. Method 2: print the variable by replacing it with sed. Replace the number in the variable with null, if the variable is null after replacement, the value is an integer echo $ args | sed & #39; s/[0-9] // g & #39; if a negative number is determined, use sed to filter the negative number echo $ args | s

Method 1: Use expr to calculate the sum of the variable and an integer. If the value is normal, it is an integer. Otherwise, an error occurs. $? The value is not 0.

Expr $ args + 0 &>/dev/null


Method 2: The print variable is replaced by sed, and the number in the variable is replaced by null. If the variable is empty after replacement, it is an integer.

Echo $ args | sed's/[0-9] // G'

If a negative number is determined, use sed to filter the negative number.

Echo $ args | sed's/[0-9] // G' | sed's/-// G'


The following script uses two functions to determine the value. The code is very simple, so no comments are added.

#!/bin/bashusage(){cat <
 
  /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]&&usageargs1=$1args2=$2checkInt $args1checkInt1 $args2if[ $args1 -gt $args2 ];thenecho "yes,$args1 greate than $args2"elseecho "no,$args1 less than $args2"fi
 

This article is from the "gccmx163.com" blog, please be sure to keep this source http://489381.blog.51cto.com/479381/1331256


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.