shell中程序的基本添加

时间:2014-05-14 14:12:43

标签: shell

我们编写了一个简单的shell脚本

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

输出:

240
82
240+82

如何正确地得到总和

3 个答案:

答案 0 :(得分:0)

在UNIX shell中有多种方法可以执行算法,但是,在我进入之前,你需要意识到除非你的shell 与大多数shell不同,否则你需要定义变量变量名称,=或值之间没有空格:var1='abc'

为此,我假设你 使用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

答案 1 :(得分:0)

bc命令应该可以正常工作

echo "4+10" | bc

答案 2 :(得分:0)

为了帮助您入门,这里有一个带注释,语法正确的代码版本,它应该适用于所有与POSIX兼容的shell(例如bash):< / p>

#!/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"

一般提示: