Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

The only calculator I know is bc. I want to add 1 to a variable, and output to another variable.

I got the nextnum variable from counting string in a file:

nextnum=`grep -o stringtocount file.tpl.php | wc -w`

Lets say the nextnum value is 1. When added with 1, it will become 2. To calculate, I run:

rownum=`$nextnum+1 | bc`

but got error:

1+1: command not found

I just failed in calculation part. I've tried changing the backtick but still not works. I have no idea how to calculate variables and output it to another variable.

share|improve this question
1  
Have a look at unix.stackexchange.com/questions/40786/… –  Ulrich Dangel Oct 8 '12 at 10:08

4 Answers 4

up vote 7 down vote accepted

The substring inside the ` ` must be a valid command itself:

rownum=`echo $nextnum+1 | bc`

But is preferable to use $( ) instead of ` `:

rownum=$(echo $nextnum+1 | bc)

But there is no need for bc, the shell is able to do integer arithmetic:

rownum=$((nextnum+1))

Or even simpler in bash and ksh:

((rownum=nextnum+1))
share|improve this answer

Absolutely right and complete the suggested solutions, just to mention the way it has to be done in former times when only the Bourne-Shell was available, that's the way it likes it:

rownum=`expr $nextnum + 1` 
share|improve this answer

I would use (as was mentioned before) rownum=$((nextnum+1)) or ((rownum=nextnum+1)) but if you prefer an standard command you can use the let command, like let rownum=$nextnum+1

share|improve this answer
1  
Calling let a “standard command” is very misleading. $((…)) is standard (POSIX) syntax whereas let is a ksh (and bash, zsh) extension. –  Gilles Oct 8 '12 at 23:07

You can also use built in arithmetic in bash

rownum=$((nextnum+1))

which would be slightly faster

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.