Basic addition of program in shell

2020-03-31 07:25发布

问题:

we have written a simple shell script

cd location\address

var1='grep -w -c exception server.log
var2='grep -w -c exception server.log.1

var3= $var1 + $var2

echo $var3
echo $var3
echo 'addition of exception : ' $var3

Output:

240
82
240+82

How to get the summation properly

回答1:

To help you get started, here's an annotated, syntactically correct version of your code that should work in all POSIX-compatible shells (e.g., bash):

#!/bin/sh

# Note that '/' (not '\') must be used as the path separator.    
cd location/address

# Capture command output using *command substitution*, `$(...)`
# Note: NO spaces around `=` are allowed.
var1=$(grep -w -c exception server.log)
var2=$(grep -w -c exception server.log.1)

# Use *arithmetic expansion*, `$((...))`, to perform integer calculations.
# Note: Inside `$((...))`, the prefix `$` is optional when referencing variables.
var3=$(( var1 + var2 ))

# Generally, it's better to *double*-quote variable references to
# make sure they're output unmodified - unquoted, they are subject to
# interpretation by the shell (so-called *shell expansions*).
echo "$var1"
echo "$var2"

# Output the result of the calculation. Note the use of just one, double-quoted
# string with an embedded variable reference.
# (By contrast, a *single*-quoted string would be used verbatim - no expansions.)
echo "sum of exceptions: $var3"

General tips:

  • http://shellcheck.net is an excellent tool for syntax-checking shell code.
  • http://explainshell.com is a great site that explains a given command line based on man pages.
  • Resources for learning bash, probably the most widely used POSIX-compatible shell:
    • Introduction: http://www.faqs.org/docs/Linux-HOWTO/Bash-Prog-Intro-HOWTO.html
    • Guide: http://mywiki.wooledge.org/BashGuide
    • Cheat sheet: http://mywiki.wooledge.org/BashSheet


回答2:

There are multiple ways to perform arithmetic in UNIX shells, however, before I get into that you need to realize that unless your shell is just different than most shells, you need to define variables as such without whitespace between the variable name, the =, or the value: var1='abc'

For this, I'm going to assume that you're using bash

echo $((( 1 + 10 )))
echo $[ 1 + 10 ]
# 11

var=0
((++var))
echo $var
# 1 

((++var))
echo $var
# 2

((--var))
echo $var
# 2

((var = 1 + 2))
echo $var
# 3

let "var = 3 + 1"  # let is another way of writing `(( ... ))`
echo $var
# 4

echo $(( 1 + 2 ))
# 3

(((var = 20 + 1)))
echo $var
# 21


回答3:

bc command should work

echo "4+10" | bc


标签: shell