문제

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

도움이 되었습니까?

해결책

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:

다른 팁

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

bc command should work

echo "4+10" | bc
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top