Basic addition of program in shell

2020-03-31 06:55发布

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

标签: shell
3条回答
Evening l夕情丶
2楼-- · 2020-03-31 07:30

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楼-- · 2020-03-31 07:32

bc command should work

echo "4+10" | bc
查看更多
孤傲高冷的网名
4楼-- · 2020-03-31 07:49

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:

查看更多
登录 后发表回答