Tags

, , , , , , , , , , , , , , ,

These are based on the type of work I am interested in, i.e. scientific programming: you won’t see much about character strings in this post since we are mostly interested in numbers!

These can all be directly typed in the BASH prompt. Semicolons basically indicate the start of a new statement: you may put them in separate lines; and in that case, do not put the semicolon between the statements typed in different lines. The dollar sign ($) at the beginning of the command line indicates the command prompt and it is not a part of the command!

1. The basic
Print the sum of two integers:

$ echo $((2+3))
The two pairs of parentheses interpret them as numbers. You can also use square brackets (just a single pair):

$ echo $[2+3].

For floating point numbers use bc.

Variable substitutions may be done as
$ num1=10; num2=20; echo $(($num1+$num2))
(no space between the equality sign and the variable/number)

2. Conditional block: arithmetic conditional operators are eq, lt, le, gt and ge:

$ i=10; j=20; if [ $i -lt $j ]; then echo "$i<$j? True"; fi
$ i=$RANDOM;j=$RANDOM; if [ $i -lt $j ]; then echo "i=$i is less than j=$j"; else echo "i=$i is NOT less than j=$j";fi
($RANDOM equals a random number at each invocation)

Notice the  spaces between the square brackets and the expression within it.

3. Array:
Assignment:

$ arr=(10 11 12)
which is the same as

$ arr[0]=10; arr[1]=11; arr[2]=12

Following constructs show how you can actually access the array (link)

$ echo ${arr[2]}  # The 3rd element of the array
$ echo ${arr[*]}  # All of the items in the array
$ echo ${!arr[*]} # All of the indexes in the array
$ echo ${#arr[*]} # Number of items in the array
$ echo ${#arr[0]} # Length of item zero

4. For loop

$ for (( c=1; c<=5; c++ )); do echo "c = $c"; done            # C-style
$ for c in 1 2 3 4 5; do echo "c = $c"; done                  # List
$ arr=(1 2 3 4 5); for c in ${arr[*]}; do echo "c = $c"; done # Explicit array
$ for c in {1..5}; do echo "c = $c"; done                     # 1 thru' 5 with unit intervals
$ for c in {0..10..2}; do echo "c = $c"; done                 # 0 thru' 10 with interval=2

5. While and until loops
$ c=0; while [ $c -lt 10 ]; do echo "c = $c"; let c++; done
You may replace “let c++” by “((c++))”.

$ c=20; until [ $c -lt 10 ]; do echo "c = $c"; let c--; done

6. User input
Use read command to read in user input, e.g.
$ echo "Enter two integers"; read num1 num2; echo "$num1+$num2=$((num1+num2))"
In the second echo statement, when num1 and num2 are not enclosed within two pairs of parentheses they are treated as character strings, whereas in the last part the double parentheses cause them to be treated as numbers.

N.B. For the above loops and blocks, a line break between do or then and the statement that immediately follows it is allowed.

Reference: link.

Advertisements