Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Prerequisites
  • Bash let
  • How to use bash let
  • Conclusion

Bash let with Examples

In bash, all variables are treated as strings. You cannot perform arithmetic operations on variables as you would normally do in other programming languages since bash interprets them as strings. To overcome this, bash has a built-in tool named let. Using the let command, you can declare a variable and perform arithmetic operations during the assignment.

Prerequisites

  • A text editor

  • Access to a terminal

Bash let

Bash let is a simple built-in utility available on all Linux systems. It directs bash to evaluate arithmetic expressions. Using this command you can perform bitwise operations as well. Your variable computations do not expect you to add the $ symbol to represent variables.

Here’s the syntax:

let <expression>

Where expression is the expression to be carried out.

How to use bash let

In this section, we are going to learn how we can make use of the let command to evaluate strings as numbers. We will carry out arithmetic, bitwise, and increments and decrements operations on variables using let. We will also understand the scope of the variables.

1. Evaluate Strings as Numbers

The bash variables, by default, are of strings datatype. To carry out the conversion and evaluate them as numbers, we can use the let command.

Let’s create a script (letScript1.sh) by opening your favorite editor. Put the following contents and save it:

#!/bin/bashlet i=5echo i is $i j=10 k=jecho Without let j is $j and k is $k #Without let k will store the string value j let j=10 k=jecho With let j is $j and k is $k #Assigning the same value to another variable

The above example assigns a numeric value to the variable. Another interesting thing to note is that let command allows us to assign the same value to a new variable.

2. Basic arithmetic operations

The basic arithmetic operators are:

  • Addition (+)

  • Subtraction (-)

  • Multiplication (*)

  • Division (/)

  • Exponential (**)

  • Modulus (%)

Example:

#!/bin/bashlet a=4let b=2c=6d=3echo "------------------WITHOUT USING LET TO PERFORM ADDITION------------------"result=$a+$becho Sum of $a and $b is $result #Alternativelyresult2=$c+$decho $c+$d is $result2 echo "------------------USING LET TO PERFORM ADDITION------------------"let result=$a+$becho $a+$b is $result #Alternatively we can use let as followslet result2=$c+$decho $c+$d is $result2 echo "------------------USING LET TO PERFORM SUBTRACTION------------------"let result=$a-$becho $a-$b is $result #Alternatively we can use let as follows:let result2=$c-$decho $c-$d is $result2 echo "------------------USING LET TO PERFORM MULTIPLICATION------------------"let result=$a*$becho $a*$b is $result #Alternatively we can use let as follows:let result2=$c*$decho $c*$d is $result2 echo "------------------USING LET TO PERFORM DIVISION------------------"let result=$a/$becho $a/$b is $result #Alternatively we can use let as follows:let result2=$c/$decho $c/$d is $result2 echo "------------------USING LET TO PERFORM EXPONENTIAL------------------"let result=$a**$becho $a^$b is $result #Alternatively we can use let as follows:let result2=$c**$decho $c^$d is $result2 echo "------------------USING LET TO PERFORM MODULUS ------------------"let result=$a%$becho $a%$b is $result #Alternatively we can use let as follows:let result2=$c%$decho $c%$d is $result2

As we can see, without using the let command, bash will interpret the variables as strings and will print the expression without evaluating it. With let, we can perform the basic arithmetic functionalities. We can either explicitly declare the variables using let and perform the operations or simply use let to declare the result where the expression evaluation takes place.

3. Increments and Decrements Operators

The increments and decrements can be categorized into 3 categories:

  • Post-increment(i++) and Post-decrement(i--): Using let, we can interpret the numerical value of the variable then increase or decrease by 1.

  • Pre-increment(++i) and Pre-decrement(--i): When used with let, this operation results in an increase or a decrease of the value by 1 and then the interpretation of the numeric variable takes place.

  • Unary plus(+i) and Unary minus(-i): This operation appends a plus (+) or a minus (-) sign to the numeric value. It other words, the expression is multiplied by 1 or -1

Example:

#!/bin/bashecho "------------------POST------------------"let a=4let b=102 let z=a++echo $a $z let y=b--echo $b $y echo "------------------PRE------------------"let a=4let b=102 let z=++aecho $a $z let y=--becho $b $y echo "------------------UNARY------------------"let a=4let b=-102 let z=-aecho $a $z let y=+becho $b $y

From the above example we can see increments and decrements can be performed with the help of let command. With post operations, variables z and y are assigned the values of a and b respectively before the increment has happened. However, with pre operations, the values are altered after which they get stored in the variables z and y.

4. Bitwise operations

The following bitwise operators can be used with let.

  • Bitwise negation(~)

  • Bitwise shift left

  • Bitwise shift right

  • Bitwise AND

  • Bitwise OR

  • Bitwise XOR

Here’s an example:

#!/bin/bashlet a=4 #000100let b=2 #000010 echo "------------------ USING LET FOR BITWISE NEGATION------------------"let result=~a echo Negation of $a is $result echo "------------------ USING LET FOR LEFT SHIFT------------------"let "result=a<<2"echo Left shift of $a is $result echo "------------------ USING LET FOR RIGHT SHIFT------------------"let "result=a>>2"echo Right shift of $a is $result echo "------------------ USING LET FOR BITWISE AND------------------"let "result=a&b" echo $a AND $b is $result echo "------------------ USING LET FOR BITWISE OR------------------"let "result=a|b" echo $a OR $b is $result echo "------------------ USING LET FOR BITWISE XOR------------------"let "result=a^ b" echo $a XOR $b is $result

Using let we perform bitwise operations. The binary value of 4 is 00000100. Negation will flip 4 to a binary value of 11111011, which is represented as -5 in 2’s complement. A single bitwise left shift is multiplication by 2. Doing it twice results in multiplication by 4. Similarly, a single right shift results in the division of the number by 2.

Further, a bitwise AND compares two bits and returns 1 if both are 1, otherwise 0. A bitwise OR also does the bitwise comparison, returning 1 even if one of the bits is 1, otherwise 0. XOR returns 0 if two bits are similar otherwise 1 2 in binary= 00000010 4 in binary = 00000100 Negation of 4 = ~4 = 11111011 = -5 2 Bitwise left shift of 4 = 4<<2 = 00000100 -> 00001000-> 00010000 = 16 2 Bitwise right shift of 4 = 4 >>2 = 00000100 -> 00000010-> 00000001 = 1 Bitwise 4 and 2 = 4&2 = 00000100 & 00000010 =00000000 = 0 Bitwise 4 or 2= 4|2 = 00000100 | 00000010 =00000110 = 6 Bitwise 4 xor 2= 4^2 = 00000100 ^ 00000010 =00000110 = 6

5. Scope of variables

The let command creates a local scope for the variables on which it acts. If you have any predefined variable existing, it will get overwritten. When a variable set in its local scope and its effective value is not yet established, the value does not update when we evaluate it.

Example:

#!/bin/bashecho "------------------ ONE------------------"j=10let i=5let j=iecho i and j are $i and $j echo "------------------ TWO------------------"let i=5let inc=i++echo i and inc are $i and $inc echo "------------------ THREE------------------"let i=5let inc=++iecho i and inc are $i and $inc

The variable j was initialized to 10. However, after using let command, it was overwritten to the value stored in the variable i. In the next case, we can see the value of inc does not increase. However, in the final case, the evaluation of i happened before the assignment to the variable inc. As a result both i and inc hold the value 6.

Conclusion

Takeaway points from this tutorial

  • All bash variables are strings so to process them as numeric values, bash offers a simple command called let.

  • It is a pretty useful bash functionality to carry out arithmetic and bitwise operations on numbers.

  • We have also learned about the scope of the variables in detail.

PreviousBash readarray with ExamplesNextBash expr with Examples

Last updated 1 year ago

using let bitwise operation
using let  assigns a numeric value to the variable
using let basic arithmetic operations
scope of the variable
using let increment and decrement