Shell Implements simple calculator function

Source: Internet
Author: User

The Shell implements a simple calculator function with the following script:

[[email protected] scripts]# Cat Jisuan.sh#!/bin/bashprint_usage () {printf $ "usage:$0 NUM1 {+|-|*|/} num2\n" Exit 1} #判断传入的参数是不是3个if [$#-ne 3] then print_usagefifirstnum=$1secondnum=$3op=$2# to determine the incoming parameters to see if it is reasonable if [-n "' Echo $firstnum |s Ed ' s/[0-9]//g ' "];then print_usagefiif [" $op "! =" + "]&&[" $op "! ="-"]&&[" $op "! =" * "]&& ["$op"! = "/"];then Print_usagefiif [-N "' Echo $secondnum |sed ' s/[0-9]//g '"];then Print_usagefiecho "${firstnum} ${op}${secondnum}=$ ((${firstnum}${op}${secondnum})) "

Debugging:

[[email protected] scripts]# sh -x jisuan.sh  6 + 4+  ' ['  3 -ne 3  '] ' + firstnum=6+ secondnum=4+ op=++ + sed  ' s/[0-9]//g ' ++ echo 6+  ' ['  -n  '   '] ' +  ' ['  +  '! = '  +  ' ++ sed  ' s/[0-9]//g ' ++ echo 4+  ' ['  -n  '   '] ' + echo  6+4=106+4=10[[email protected] scripts]# sh -x jisuan.sh 5 \* 5+   ' ['  3 -ne 3  '] ' + firstnum=5+ secondnum=5+ op= ' * ' ++ sed  ' s/[ 0-9]//g ' ++ echo 5+  ' ['  -n  '   '] ' +  ' ['   ' * '   '! = '  +  '] ' +   ' ['   ' * '   '! = '  -  '] ' +  ' ['   ' * '   '! = '   ' * '   '] ' ++ sed  ' /[0-9]//g ' ++ echo 5+  ' ['  -n  '   '] ' + echo  ' 5*5=25 ' 5*5=25 

Attention:

    1. "-X" means debugging, and you can see the steps performed

    2. The corresponding "*" needs to be escaped with "\"

This article is from the "Knowledge Change Destiny" blog, please be sure to keep this source http://ahtornado.blog.51cto.com/4826737/1927919

Shell Implements simple calculator function

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.