120 likes | 291 Views
BASH Scripting. Arithmetic Operations. Objectives. Reinforce basic scripting: Variables I/O Execution Introduce Arithmetic operations: integer operations. Overview. Arithmetic operations ** (exponentiation) *,/,% (multiplication, division, remainder) ++,-- (increment, decrement)
E N D
BASH Scripting Arithmetic Operations
Objectives • Reinforce basic scripting: • Variables • I/O • Execution • Introduce Arithmetic operations: • integer operations
Overview • Arithmetic operations • ** (exponentiation) • *,/,% (multiplication, division, remainder) • ++,-- (increment, decrement) • +,- (addition, subtraction)
Arithmetic Operations • Arithmetic Operators (binary) • ** (exponentiation) order is left to right • *,/,% (multiplication, division, remainder) • +,- (addition, subtraction) • Assignment (op= operations above) • exprvar1opvar2 does not include ** op, spaces required • letvar=var1opvar2 # Note no spaces • (( var = var1 op var2)) # space independent • declare [-ix] var=var1opvar2 • Arithmetic Operators (unary) • ++,-- (increment, decrement)
declare • declare is a bash command that will establish the type of variable and optionally give it an initial value. • Format: declare [options] var[={val|expr}] • Selected options:
Sample of Arithmetic/AssignmentStatements • Integer • expr 3 / 5 • expr 3 \* 5 • expr 3 ** 5 # INVALID!!!! • letval=3*4 # see caution below! • (( val = 3 * 5 )) • (( val = 3 ** 5 )) Do NOT use val=3*4 to do arithmetic, you must use the let command (unless val has been declared to be an integer).
Sample scripts • comp – shows declare and (( )) operators declare -i testval=20 declare -i count=2 (( result = $testval * $count )) echo $result
Array Example array=(red green blue yellow magenta) len=${#array[*]} echo "The array has $len members. They are:" i=0 while [ $i -lt $len ]; do echo "$i: ${array[$i]}" let i++ done
Results of Running Script The array has 5 members. They are: 0: red 1: green 2: blue 3: yellow 4: magenta
Lucky Numbers Assignment Accept birthday (1-31) and birth month (1-12) from the user. Use that information to generate 6 random numbers between 1 and 45 to represent lucky lotto numbers. Your six numbers need to be stored in an array. The array will have indices 0-5. You will use arithmetic manipulations of the birth day and month to generate the lucky numbers. Everyone with the same birthday and month will get the same lucky numbers – everyone with a different birthday and month will get different lucky numbers. There can be no duplicates in the lucky numbers.