0% found this document useful (0 votes)
23 views10 pages

Advanced Shell Programming Techniques

The document describes an experiment on advanced shell programming. It aims to evaluate programming skills using shell scripts with decision making and looping techniques. Students will create shell scripts that use test conditions and if/else statements to make decisions. They will also create scripts that use for and while loops to perform repetitive tasks. The procedure instructs students to write scripts that demonstrate if/else logic, file testing, variable testing, and looping using lists and user input.

Uploaded by

Jong Franco
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views10 pages

Advanced Shell Programming Techniques

The document describes an experiment on advanced shell programming. It aims to evaluate programming skills using shell scripts with decision making and looping techniques. Students will create shell scripts that use test conditions and if/else statements to make decisions. They will also create scripts that use for and while loops to perform repetitive tasks. The procedure instructs students to write scripts that demonstrate if/else logic, file testing, variable testing, and looping using lists and user input.

Uploaded by

Jong Franco
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Experiment No.

___9__   
ADVANCED SHELL PROGRAMMING   

1. Objective(s):   
​The activity aims
1.1 To evaluate programming skills using advanced shell programming
1.2 To create shell scripts with decision making techniques

2. Intended Learning Outcomes (ILOs):   


The students shall be able to:
[Link] shell scripts with test conditions
[Link] shell scripts with looping techniques

3. Discussion (not more than 300 words):   

Just like in any programming language, shell programming is also equipped with decision making
features. In such a case, you provide two alternative sets of commands, and the shell program executes
the set of commands depending on a specified criteria.

4. Resources:   
Personal computer with Unix or unix-based operating system

5. Procedure:   
5.1. Start a terminal session with your unix or unix-based operating system.

5.2. Create and test shell scripts decision-making and looping techniques

5.2.1 Making Decisions with if. Making decisions has always been part of our daily lives. Solving
the exercises in this manual or not is a decision that the students have to make if you want
to facilitate the learning of the UNIX operating system.

Just like in any programming language, shell programming is also equipped with decision
making features. In such a case, you provide two alternative sets of commands, and the
shell program executes the set of commands depending on a specified criteria.
The if command allows the shell program to make a decision, that is by evaluating certain
conditions within the program. The shell then executes the set of command where the
condition evaluates to true and ignores the other set of command.

The Concept of Success and Failure  

The decision making process of the UNIX operating system is based on the concept of
success and failure. The decision depends on the individual commands. But, what is
success and what is failure. Whenever a command completes its task without error, then
the command is successful. On the other hand, when the command aborts and displays an
error, then the command is a failure. For example, listing the permission of a file, when a
file is not existent or printing to an unknown printer.

The Basic Format of the if Command  

The simplest format of the if command is as follows:


if
​One or more commands
​then
​One or more commands
​fi
Whenever the shell encounters the structure above, it executes all commands between the
if and the then commands. The shell checks on the last of these commands. If the last
command succeeds, then the shell executes the commands between the then and the fi;
otherwise, the commands are ignored.
The fi, if backwards is the tag indicating the end of an if statement. If only a single
command follows the if, it can be written on the same line as the if.
The exercise below shows how the if command is used in a program:
5.2.2 The else clause. The else clause gives an alternative whenever the if command evaluates to
false. The else is used as follows:
if
​One or more commands
t​ hen
​One or more commands
e​ lse
​One or more commands
f​ i
The commands between the if and the then are always executed.
∙ ​If the last command is successful, then the set of commands between the then and the
else is executed. However,
∙ ​Otherwise, the set of commands between the else and the fi is executed.
Only one set of command is executed. It can never be both!
Modify the previous exercise to give a more informative result as follows:
The
output of program remains the same as without the clause when the ls command finds the
file. However, if it doesn’t, the output will be different. The program displays additional
message when the file is not found, as follows:

5.2.3
Performing tests with test. The test command enables you to evaluate for conditions other than
success or failure. The command succeeds or fails based on whether a given condition is true or
false.

Using File Tests  

The test command can determine whether a specified file meets a desired criterion. It has
the following form:
test [option] ​filename
Commonly Used Options for the test Command
Option Action

-f Checks whether a file exists and is a regular file

-d Checks whether a file exists and is a directory

-r Checks whether a file exists and is readable

-w Checks whether a file exists and is writable

-x Checks whether a file exists and is executable

-s Checks whether a file exists and has a size greater than zero

Modify the previous exercise and use the test command to produce a better output:

The program behaves similar to the previous program, if the file is available. It behaves
differently, otherwise. There was no error message displayed, if the file is not found; rather,
just the friendly message is display.
Alternative Format of test  

The test command has an alternative format that doesn’t even use the word test. That is,
by enclosing the condition in brackets, as follows:
[ condition ]
As in,
If [ -f $filename ]
Please observe the spaces between the condition and the brackets.

5.2.4 Performing Variable Tests. Probably the most important use of for test is checking the value
of a variable. This test falls in two classes: string tests and numeric tests. [Link]. The
format of the string test is as follows:
test ​value operation value
where: value represents a string, or a variable that contains a string
operation can either be = (equality) or != (difference)

[Link]. The format of the numeric tests is as follows:


test ​value operation value
where:value represents a number or a variable that contains a number
The operation is one of the following

Operation Meaning

-eq Numbers are equal

-ne Numbers are not equal

-lt The first number is less than the second

-le The first number is less than or equal to the second

-gt The first number is greater than the second

-ge The first number is greater than or equal to the second

5.2.5 Using Programming Loops. Perhaps the most important ability of any programming language
is performing repetitive tasks. People get bored and tired doing the same thing over and
over again, but not the computers. They can perform repeated works with extreme
efficiency and accuracy.
A loop is a generic computer term for an operation done repeatedly. There are two
commands that enable you to repeat tasks: for and while.
[Link]. Looping with for. The for command repeatedly performs a set of commands on a
list of items, which could be anything such as user names, file names, a list of
students. The for command has this format:

for ​variable
i​ n list
do
​commands
done

Alternatively, the for and in can be written on the same line as follows:

for ​variable i​ n list


do
​commands
done

The commands between the do and done will be performed as many times as
there are items in the list. The first time that the commands are executed, the
variable takes the value of the first item in the list; the second time, gets the
value of the second item in the list, and so on until all the items in the list are
assigned.
The exercise below lists the shell programs of a directory:
[Link]. Looping with while. The shell’s other looping command is while, and uses the
following format:

while
One or more commands
do
One or more commands
done

The while loop resembles the if command. In fact, the while command works the
same way as the if command. It executes all the commands between the while
and the do statements, checking whether the last command succeeds or fails. If
the last command succeeds, the commands between the do and the done
statements will be executed; otherwise, if it fails, these commands are skipped and
shell executes the commands following the done statement.
The exercise below demonstrates the use of the while command. It asks for the
subject you enrolled, one per line. The program asks the same question
repeatedly until you enter the word ‘exit’.
Course: Experiment No.:   
Group No.: Section:   
Group Members: Date Performed:   
Date Submitted:   
Instructor:   

6. Data and Results:  


7. Conclusion:   
8. Assessment (Rubric for Laboratory Performance):  

Common questions

Powered by AI

File tests in shell scripts, using the 'test' command with options like '-f', '-d', '-r', '-w', '-x', and '-s', enable scripts to handle file-based operations effectively by checking attributes like existence, readability, and writability. For instance, a script can verify if a file exists before attempting to read it to avoid errors or check if a file is writable or executable before performing modifications or executions . By integrating these checks, scripts become more reliable, reducing the probability of runtime errors caused by file handling operations.

The 'test' command enhances decision-making in shell scripts by allowing for evaluations beyond simple command success or failure. It can check file attributes, such as whether a file exists or is readable, and evaluate variable conditions, such as string equality or numeric comparisons . Common use cases include checking the existence of files and directories, confirming variable values, and determining permissions, making scripts more robust and better at pre-emptively handling errors and unexpected conditions.

The 'for' and 'while' loop constructs increase efficiency by automating repetitive tasks, which a computer can perform consistently without error . 'For' loops iterate over a predefined set of items, executing the loop's commands for each item, which is useful for tasks like processing lists of files or user inputs. 'While' loops, on the other hand, execute as long as a certain condition remains true, allowing for dynamic iteration until a condition changes, such as processing user input until a sentinel value is entered . This makes 'while' loops more suited to scenarios where the number of iterations is not known beforehand.

The primary decision-making commands used in advanced shell programming are the 'if' command and the 'else' clause. The 'if' command evaluates conditions and executes commands based on whether the conditions are true. It executes commands between the 'then' and 'fi' if the condition evaluates to true. The 'else' clause provides an alternative set of commands to execute if the 'if' condition evaluates to false . This structure mimics conditional execution found in other programming languages, allowing scripts to dynamically respond to varying runtime conditions.

String and numeric tests contribute to the robustness of program execution by allowing precise condition evaluations, ensuring operations only commence when specific criteria are satisfied. String tests, using '=' or '!=', handle string comparisons, vital in validating input or configuration settings. Numeric tests, such as '-eq', '-ne', '-lt', enhance control by enabling numeric evaluations for loop iterations or thresholds . These tests prevent invalid operations, ensure expected script operation flow, and provide safeguards by enabling the script to preemptively handle potential exceptions or invalid states.

Understanding the concept of success and failure is crucial because it underpins decision-making in Unix shell programming. Commands are executed depending on whether prior commands succeed (exit with status 0) or fail (non-zero status). This binary evaluation model informs the execution flow, such as proceeding to 'then' commands on success or defaulting to 'else' actions on failure. Recognizing how success and failure influence conditional workflows allows programmers to write scripts that predictably adapt to environments, handle errors gracefully, and execute only feasible commands, ensuring script stability and reliability.

Educational objectives achieved through learning advanced shell programming include developing programming skills pertinent to efficiently using Unix-based systems. Students learn to create shell scripts with decision-making techniques and loops, handle file operations deftly using 'if', 'else', and 'test' commands, and increase familiarity with Unix commands and scripting concepts . By mastering these techniques, students can automate system tasks, enhance their coding efficiency, and leverage shell programming's power in various problem-solving contexts, which aligns with objectives like improving coding proficiency and critical thinking in programming scenarios.

The 'else' clause is essential in scenarios requiring alternative actions if an initial condition fails, such as providing feedback when a file does not exist or executing alternative logic when a user input condition is unmet . This necessity reflects the inherently conditional nature of programming where different pathways are defined to account for varied outcomes, ensuring scripts can handle failure scenarios gracefully by defaulting to secondary instructions. This illustrates how scripts can dynamically respond to varying conditions, ensuring consistent operational flow and robustness.

Interactive shell scripting with loops and conditionals aligns with real-world problem-solving by applying iterative and conditional foresight to operational tasks, akin to logical processes humans use in decision-making and troubleshooting. Loops allow the repeated execution of tasks to address dynamic input or datasets, analogous to repeated experimental iterations in problem-solving. Conditionals reflect logical branches akin to decision trees, directing actions based on outcomes or environmental states . This structured yet flexible approach mirrors systematic methodologies in troubleshooting, facilitating problem-solving that requires adaptability and precision, both integral to effective real-world solutions.

Looping constructs emulate decision-making processes by executing a block of commands based on dynamic conditions, mirroring everyday logical operation sequencing, like repetitive checking and decisions based on evolving states. 'For' and 'while' loops facilitate repeated decision-making by continuously evaluating conditions: 'for' loops iterate over items (e.g., checking each file for a condition), and 'while' loops continually check a changing condition (e.g., user input until exit condition). These mimic conversational patterns where decisions are reevaluated repeatedly until a goal is met or a terminating condition encountered.

You might also like