evaluate expression in linux

How to Evaluate Expression in Shell Script

Shell script is a powerful way to automate tasks and run programs. You can also evaluate expressions and do calculations in shell script. There are several ways to evaluate expression in shell script. Here are the steps to do it in Linux.

How to Evaluate Expression in Shell Script

Like other programming languages, bash shell does not have types for variables. Every variable is string by default. Here is an example where we declare a variable without any attributes.

$ declare A=2+2
$ echo $A

As you can see above, the expression ‘2+2’ was treated as string and not integer. If you want the above variable to be interpreted as arithmetic integer, use -i attribute.

$ declare -i A=2+2
$ echo $A

Please note, even in this case, the variable $A is a string. It is just that when we use -i option, it will parse expressions as integer before assigning it. If there is a parsing error, it will drop fractional part of number.

$ A=test
$ echo $A

Alternatively, you can use let statement to declare variable and assign result of arithmetic operation during assignment. Also, you can assign it to something other than an integer later on. Here is an example where we first assign value of expression ‘2+2’ to a variable, and then change it to a string.

$ let A=2+2
$ echo $A
$ A=test
$ echo $A

Now we will look at certain ways to access these variables in Linux. The simplest way to access a variable is to prepend $ at its beginning.

$ A=2
$ echo $A

If you want to include another string immediately before or after the variable’s value, you need to enclose the variable in ${…}. Here is an example.

$ echo ${A}string

Instead of direct substitution, if you want to evaluate the value of an expression, you can enclose the expression within $(…)

$ A=2;B=2
$ echo $((A+B+1))

You can also use expr command followed by the expression to be evaluated.

$ expr 2 + 3
$ expr 2 \< 3
$ expr substr abcdef 1 4

Please note, we have used backslash ‘\’ to escape operator ‘<‘ in the above command.

In this article, we have learnt several ways to evaluate expression in shell script in Linux.

Also read:

What does $() and ${} mean in shell script
How to Run C Program in Linux
How to Delete Write Protected File in Linux
How to Suspend Process in Linux
How to Run Linux Command Without Logging History

Leave a Reply

Your email address will not be published. Required fields are marked *