Make your ~/bin directory your working directory (cd ~/bin). Exercise 1: Write a
ID: 3825783 • Letter: M
Question
Make your ~/bin directory your working directory (cd ~/bin). Exercise 1: Write a Bash script named ic11_ex1 that displays (sends to standard output) the name of the calling program (script), the number of positional parameters, and a list of positional parameters (command line arguments). Include the #! line and a comment in your script file. Remember to make the file executable. Test the script with 0, 1, and 5 positional parameters. Exercise 2: Write a Bash script named ic11_ex2 that prompts the user with >> to enter a string and reads that string of text from the user. If the user enters a non-null string, the script displays “You entered: followed by the string”; otherwise it displays “Where is your input?.” Use an if...then...else control structure to implement the two-way branch in the script. Exercise 3: Write a Bash script named ic11_ex3 that prompts the user to enter the side of a cube (only integers) and displays the volume of the cube. Test/run your script and make sure is working properly.
Explanation / Answer
1)
vi ic11_ex1
==
#!/bin/ksh
#$0 is the variable which stores the name of calling program
echo "NAME OF CALLING PROGRAM IS $0"
echo "THE NUMBER OF POSITONAL PARAMETERS ARE $#"
echo "LIST OF POSTIONAL PARAMETERS ARE $@"
save this as ic11_ex1
after that
type
chmod 755 ic11_ex1
./ic11_ex1 0 1 5
NAME OF CALLING PROGRAM IS ./ic11_ex1
THE NUMBER OF POSITONAL PARAMETERS ARE 3
LIST OF POSTIONAL PARAMETERS ARE 0 1 5
2)
ic11_ex2
==============
#!/bin/bash
echo ">>"
read name
if [ ! -z "$name" ]
then
echo "you entered: "
echo $name
else
echo "Where is your input ?"
fi
output: for null
./ic11_ex2
>>
Where is your input ?
==
output for not null
./ic11_ex2
>>
abc
you entered: abc
==================
3)
ic11_ex3
================
#!/bin/bash
function is_integer() {
printf "%d" $1 > /dev/null 2>&1
return $?
}
if [ $# -eq 0 ]
then
echo "At least one argument expected"
exit
fi
if [ $# -gt 1 ]
then
echo "only one argument expected"
exit
fi
if [ $1 -lt 0 ]
then
echo "Side of cube must be positive"
exit
fi
if ! is_integer $1;
then
echo -e " Integer argument expected"
exit 1
fi
side=$1
volume=`expr $side * $side * $side`
echo "Volume of cube with side $side unit= $volume unit"
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.