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
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It only takes a minute to sign up.
Sign up to join this communityBash 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.
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.