Saturday, November 30, 2019

[Unix / Linux Shell Tutorial - Lession7] Arithmetic

  1. #!/bin/bash
  2. # Basic arithmetic using let
  3. let a=5+4
  4. echo $a # 9
  5. let "a = 5 + 4"
  6. echo $a # 9
  7. let a++
  8. echo $a # 10
  9. let "a = 4 * 5"
  10. echo $a # 20
  11. let "a = $1 + 30"
  12. echo $a # 30 + first command line argument

OperatorOperation
+, -, \*, /addition, subtraction, multiply, divide
var++Increase the variable var by 1
var--Decrease the variable var by 1
%Modulus (Return the remainder after division)
Example2
  1. #!/bin/bash
  2. # Basic arithmetic using expr
  3. expr 5 + 4
  4. expr "5 + 4"
  5. expr 5+4
  6. expr 5 \* $1
  7. expr 11 % 2
  8. a=$( expr 10 - 3 )
  9. echo $a # 7

Example3
  1. #!/bin/bash
  2. # Basic arithmetic using double parentheses
  3. a=$(( 4 + 5 ))
  4. echo $a # 9
  5. a=$((3+5))
  6. echo $a # 8
  7. b=$(( a + 3 ))
  8. echo $b # 11
  9. b=$(( $a + 4 ))
  10. echo $b # 12
  11. (( b++ ))
  12. echo $b # 13
  13. (( b += 3 ))
  14. echo $b # 16
  15. a=$(( 4 * 5 ))
  16. echo $a # 20


Example4
  1. #!/bin/bash
  2. # Show the length of a variable.
  3. a='Hello World'
  4. echo ${#a} # 11
  5. b=4953
  6. echo ${#b} # 4





No comments:

Post a Comment

Back to Top