cat q2sh binsh res0 x0 check command line if It 2 then ech

$cat q2.sh #!/bin/sh res=0 x=0 # check command line if [$# -It 2]; then echo \"Oops! I need atleast 2 command line args\" echo \"Syntax: $0: number1 number2 ... numberN\" echo \"Example:$0 56 66 34\" exit 1 fi for i in $@ do x=expr $x + $i done res=expr $x/$# echo \"res = $res\" $./q2.sh 3 Output: Continue on question 2) $./q2.sh 12 4 8 Output:

Solution

Please find the answers below:

1) ./q2.sh 3

OUTPUT:

Oops! I need atleast 2 command line args

Syntax: q2.sh : number1 number2.......numberN

Example: q2.sh 56 66 34

Here $# gives the no:of command line arguments, thus here it is 1, which is less than 2, so according to the if condition it will give rise to the printed error statements and exit the program.

2) q2.sh 12 4 8

Here $# is 3, thus if condition was ok, then it iterates over each argument and add the sum to initial x=0.

thus it will gives : 0 + 12 =12, then 12 + 4 = 16, then 16 + 8 = 24

after loop, it will just divide the sum in x, by the no:of arguments ($#)

thus: 24 / 3 = 8

thus the output at res = 24

OUTPUT:

res = 24

 $cat q2.sh #!/bin/sh res=0 x=0 # check command line if [$# -It 2]; then echo \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site