Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

unix

I have two variables called count1 and count7

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

This shows an error "expression is not complete; more token required".

How should I add the two variables?

like image 314
suvitha Avatar asked Aug 30 '11 15:08

suvitha


People also ask

How do you store values in a variable in UNIX?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]


2 Answers

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.

like image 89
Jonathan Leffler Avatar answered Sep 16 '22 21:09

Jonathan Leffler


var=$((count7 + count1))

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

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

like image 23
Victor Odiah Avatar answered Sep 18 '22 21:09

Victor Odiah