开发者

How to add values in a variable in Unix shell scripting?

开发者 https://www.devze.com 2023-04-01 07:58 出处:网络
I have two variables called count1 and count7 count7=0 count7=$(($count7 + $count1)) This shows an error \"expression is not complete; more token req开发者_StackOverflowuired\".

I have two variables called count1 and count7

count7=0
count7=$(($count7 + $count1))

This shows an error "expression is not complete; more token req开发者_StackOverflowuired".

How should I add the two variables?


What is count1 set to? If it is not set, it looks like the empty string - and that would lead to an invalid expression. Which shell are you using?

In Bash 3.x on MacOS X 10.7.1:

$ count7=0
$ count7=$(($count7 + $count1))
-sh: 0 + : syntax error: operand expected (error token is " ")
$ count1=2
$ count7=$(($count7 + $count1))
$ echo $count7
2
$

You could also use ${count1:-0} to add 0 if $count1 is unset.


var=$((count7 + count1))

Arithmetic in bash uses $((...)) syntax.

You do not need to $ symbol within the $(( ))


In ksh ,bash ,sh:

$ count7=0                     
$ count1=5
$ 
$ (( count7 += count1 ))
$ echo $count7
$ 5


You can do this as well. Can be faster for quick calculations:

echo $[2+2]


Here's a simple example to add two variables:

var1=4
var2=3
let var3=$var1+$var2
echo $var3


the above script may not run in ksh. you have to use the 'let' opparand to assing the value and then echo it.

val1=4

val2=3

let val3=$val1+$val2

echo $val3 


 echo "$x"
    x=10
    echo "$y"`enter code here`
    y=10
    echo $[$x+$y]

Answer: 20


I don't have a unix system under my hands, but try this:

count7=$((${count7} + ${count1}))

Or maybe you have a shell that doesn't support this expression. I think bash does support it, but sh doesn't.

EDIT: There is another syntax, try:

count7=`expr $count7 + $count1`


read num1
read num2
sum=`expr $num1 + $num2`
echo $sum
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号