In: Computer Science
Write a script to display the following patterns on the screen. Number of rows and columns are taken from the command arguments; if they are missing, set default to 3 (rows) and 4 (columns). Hint: you will use a nested loop.
****
****
****
a) Display the source code in an editor (#4-11)
b) Execute your script in the terminal, and display the command and the result (#4-12)
The shell script (pattern_script.sh): (The pictures are attached below)
# pattern_script.sh
#!/usr/bin/env sh
# A shell script to print patterns on the screen.
# Rows and columns are taken from command arguments, if missing default values are taken.
defRow=3 # Default value for row
defCol=4 # Default value for column
row=${1:-$defRow} #If first argument exists, row is assigned with given value else default value
column=${2:-$defCol} #If first argument exists, column is assigned with given value else default value
for (( i = 1; i <= row; i++ ))
do
for (( j = 1 ; j <= column; j++ ))
do
echo -n "*" # Printing * for each iteration of inner loop
done
echo "" #Printing new line
done
Output 1: (Arguments 10 and 10 are passed using command "sh pattern_script.sh 10 10", number of rows and columns will be 10 and 10).
Vinny@DESKTOP-1UC0IAM MINGW64 ~/Documents/shs
$ sh pattern_script.sh 10 10
**********
**********
**********
**********
**********
**********
**********
**********
**********
**********
Output 2: (No arguments are passed in the command "sh pattern_script", hence default rows i.e. 3 and default columns i.e. 4 will be used).
Vinny@DESKTOP-1UC0IAM MINGW64 ~/Documents/shs
$ sh pattern_script.sh
****
****
****
Note: The reader has to make sure to save the shell script file in proper name and use the same name in the command with .sh extension. Passing the command line arguments is shown in the image below, reader has to make sure passing command line arguments properly.
a. Display the source code in an editor:
The editor used in this image is Visual Studio Code ( VS Code for short).
b. Execute your script in the terminal, and display the command and result.
The terminal used in this image is Git Bash: (Any shell executable terminal can be used by the reader)
Note: When code copied from above, student has to replace [NBSP] with space(' ') in the code, if found any.