1

I'm trying to convert this line of C program to bash script: C:

bin = bin+d*10^n-1;

bin,d,n are declared as int. bash:

bin=`exp $bin+$d\*10^n-1`

but it's incorrect

1 Answer 1

1

Bash has built-in functionality for arithmetic expressions. The feature is called "Arithmetic Expansion". The bash man page contains more information.

The syntax is $((expression)). In your case the script might contain the following.

#!/bin/bash

set -x

bin=1
d=2
n=3
echo $((${bin} + ${d}*10^${n}-1))

The operator precedence resembles C's but is not exactly the same, as Bash and C support different operators. Here is a useful reference: https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html#Shell-Arithmetic

The above is appropriate only because the operands are C ints. Arithmetic Expansion does not support floating-point arithmetic.

4
  • 1
    ^ in C isn't exponentiation.
    – muru
    Nov 11, 2018 at 5:34
  • I have corrected the response.
    – user891856
    Nov 11, 2018 at 6:00
  • How to do it without echo command?
    – Tu Nguyen
    Nov 11, 2018 at 14:30
  • @TuNguyen echo was used to print the result immediately. You can store it in variable like bin=$((${bin} + ${d}*10^${n}-1)) and then print it using echo $bin or use anywhere else.
    – Kulfy
    Nov 11, 2018 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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