Bash script with branching and looping
Part 1:
1. Create a variable called NAME and set it equal
to the empty string (NAME=””). Create a variable
called NAME_LENGTH and set it equal to the length
of your last name. Output the value of the
NAME variable to show that it is empty.
2. Write a FOR loop that executes as many times as there are
letters in your name (use the
NAME_LENGTH variable in your condition). Use a
CASE statement inside the loop to add letters
to NAME one at a time to spell out your last name.
Write the CASE statement so that each time
the loop executes, a single letter is added to the value of the
NAME variable (using the +
operator). Output the value of the NAME variable
after each letter is added. The 2 best ways to
write the CASE statement are:
a. Use the possible values of NAME for the cases
i. Example: if your last name is Jones, the cases would be
“”,J,Jo,Jon,Jone,Jones
b. Use the possible values of the FOR loop condition variable for
the cases
i. Example: if you last name has 5 letters, the cases would be
0,1,2,3,4,5
Part 2:
1. Use an IF statement to check that NAME contains
all the letters it should.
a. When the program runs, this should always be true by the time
you get to this point, but
it would catch an error if anything went wrong with part 1.
b. You can either check that NAME is equal to your
last name or check that the length of
NAME is equal to the value of
NAME_LENGTH.
2. If the IF statement is TRUE (meaning that NAME
is the correct length), use a WHILE loop to
remove the letters in NAME one at a time. Output
NAME after each letter is removed.
a. You can do this using the string manipulations we talked about
and the ? wildcard
character. Remember that * matches any number of any characters and
? matches any
single character. You can use the ? to remove one single character
using the remove from-the-back string manipulation
3. If the IF statement is FALSE, output “Error: NAME does not
contain the correct number of
letters.” and have the program exit.
Sample output:
./build_name.sh
L
Li
Lin
Lind
Lin
Li
L
$
#!/bin/bash
NAME=""
NAME_LENGTH=7
echo "NAME is: $NAME"
for (( i=0 ; i<${NAME_LENGTH}; i++ ));
do
case $i in
0)
NAME=$NAME'J';;
1)
NAME=$NAME'A';;
2)
NAME=$NAME'V';;
3)
NAME=$NAME'V';;
4)
NAME=$NAME'A';;
5)
NAME=$NAME'J';;
6)
NAME=$NAME'I';;
esac
echo "$NAME"
done
if [[ $NAME=="JAVVAJI" ]]; then
while [[ $NAME != ? ]] #== $?
do
NAME="${NAME::-1}"
echo $NAME
done
else
echo “Error: NAME does not contain the correct number of letters.”
exit
fi
Output:
Get Answers For Free
Most questions answered within 1 hours.