Professional Documents
Culture Documents
A top-down design is generally a plan made in plain, simple English for the
program. It is very important to note that a top-down design must be
independent of any programming language. The top-down design must never
incorporate references to library functions or syntactic elements specific to a
particular language.
That is the reason why top-down designs are written in plain English. The
concept driving a top-down design is to break up the task that a program
executes into a very few extensive subtasks.
The highest level is known as the main module, top level or level 0. At this point,
the volume of subtasks must be small. Most programs at this level usually
include three to seven subtasks. For small-sized programs, the volume of
subtasks must be at the low end of the mentioned range.
Division of tasks into subtasks essentially splits the problem into various smaller
programs, which helps developers to easily code these simpler parts. It is
usually possible that many of these subtasks are so basic that they can
immediately determine how to write the code to complete that part.
However, this is generally not the case at the top level. If a subtask takes more
than a very few lines of code, it is recommended to repeat the subdivision
process. Typically, for every subtask at top level, a new module is started at
level 1. These subtasks are then considered individually, and yet again divided
into various other subtasks. This subdivision and new level creation processes
should be continued until the coders can implement every portion of the problem
using computer code.
Example
we will use top-down design to further develop our report-generator script.
Shell Functions
Our script currently performs the following steps to generate the HTML
document:
1. Open page.
7. Output timestamp.
9. Close page.
for statement
The for loop operate on lists of items. It repeats a set of commands for
every item in a list.
Here var is the name of a variable and word1 to wordN are sequences of
characters separated by spaces (words). Each time the for loop executes,
the value of the variable var is set to the next word in the list of words,
word1 to wordN.
Syntax
for var in list
do
command 1
command 2
done
until statement
The until loop is executed as many as times the condition/command
evaluates to false. The loop terminates when the condition/command
becomes true.
Syntax
until [ conditional statement ] do
command1
command2
done
break
The break statement is used to terminate the loop and can be used
within a while, for, until, and select loops.
Syntax
break [N]
// N is the number of nested loops.
// This parameter is optional.
// By default the value of N is 1.
continue
Continue is a command which is used to skip the remaining command
inside the loop for the current iteration in for, while, and until loop.
Syntax:
continue [N]
// the optional parameter N specifies the nth enclosing loop
to continue from.
// This parameter is optional.
// By default the value of N is 1.
Example Programs
Example 1:
Implementing for loop with break statement
php
#Start of for loop
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a is equal to 5 break the loop
if [ $a == 5 ]
then
break
fi
# Print the value
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Example 2:
Implementing for loop with continue statement
php
for a in 1 2 3 4 5 6 7 8 9 10
do
# if a = 5 then continue the loop and
# don't move to line 8
if [ $a == 5 ]
then
continue
fi
echo "Iteration no $a"
done
Output
$bash -f main.sh
Iteration no 1
Iteration no 2
Iteration no 3
Iteration no 4
Iteration no 6
Iteration no 7
Iteration no 8
Iteration no 9
Iteration no 10
Example 3:
Implementing while loop
php
a=0
# -lt is less than operator
#Iterate the loop until a less than 10
while [ $a -lt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
Example 4:
Implementing until loop
php
a=0
# -gt is greater than operator
#Iterate the loop until a is greater than 10
until [ $a -gt 10 ]
do
# Print the values
echo $a
# increment the value
a=`expr $a + 1`
done
Output:
$bash -f main.sh
0
1
2
3
4
5
6
7
8
9
10
Example 5: Infinite loop
PHP
while true
do
# Command to be executed
# sleep 1 indicates it sleeps for 1 sec
echo "Hi, I am infinity loop"
sleep 1
done
Output:
$bash -f main.sh
Hi, I am infinity loop
Hi, I am infinity loop
Hi, I am infinity loop
.
.
.
.
It continues
Cmdlets
Cmdlets perform an action and typically return a Microsoft .NET object to the
next command in the pipeline. A cmdlet is a single command that participates in
the pipeline semantics of PowerShell. This includes binary (C#) cmdlets,
advanced script functions, CDXML, and Workflows.
This SDK documentation describes how to create binary cmdlets written in C#.
For information about script-based cmdlets, see:
about_Functions_Advanced
about_Functions_CmdletBindingAttribute
about_Functions_Advanced_Methods
To create a binary cmdlet, you must implement a cmdlet class that derives from
one of two specialized cmdlet base classes. The derived class must:
You can load the assembly that contains the class directly by using the Import-
Module cmdlet, or you can create a host application that loads the assembly by
using the System.Management.Automation.Runspaces.Initialsessionstate API.
Both methods provide programmatic and command-line access to the
functionality of the cmdlet.
Cmdlet Terms
Cmdlet parameter
The public properties that define the parameters that are available to the user or
to the application that is running the cmdlet. Cmdlets can have required, named,
positional, and switch parameters. Switch parameters allow you to define
parameters that are evaluated only if the parameters are specified in the call.
For more information about the different types of parameters, see Cmdlet
Parameters.
Parameter set
Dynamic parameter
System.Management.Automation.Cmdlet.BeginProcessing : Used to
provide optional one-time, pre-processing functionality for the
cmdlet.
System.Management.Automation.Cmdlet.ProcessRecord : Used to
provide record-by-record processing functionality for the cmdlet.
The System.Management.Automation.Cmdlet.ProcessRecord method
might be called any number of times, or not at all, depending on the
input of the cmdlet.
System.Management.Automation.Cmdlet.EndProcessing : Used to
provide optional one-time, post-processing functionality for the
cmdlet.
System.Management.Automation.Cmdlet.StopProcessing: Used to
stop processing when the user stops the cmdlet asynchronously (for
example, by pressing CTRL+C).
For more information about these methods, see Cmdlet Input Processing
Methods.
When you implement a cmdlet, you must override at least one of these input
processing methods. Typically, the ProcessRecord() is the method that you
override because it is called for every record that the cmdlet processes. In
contrast, the BeginProcessing() method and the EndProcessing() method
are called one time to perform pre-processing or post-processing of the records.
For more information about these methods, see Input Processing Methods.
ShouldProcess feature
PowerShell allows you to create cmdlets that prompt the user for feedback
before the cmdlet makes a change to the system. To use this feature, the cmdlet
must declare that it supports the ShouldProcess feature when you declare the
Cmdlet attribute, and the cmdlet must call
the System.Management.Automation.Cmdlet.ShouldProcess and System.Manage
ment.Automation.Cmdlet.ShouldContinue methods from within an input
processing method. For more information about how to support
the ShouldProcess functionality, see Requesting Confirmation.
Transaction
A logical group of commands that are treated as a single task. The task
automatically fails if any command in the group fails, and the user has the
choice to accept or reject the actions performed within the transaction. To
participate in a transaction, the cmdlet must declare that it supports transactions
when the Cmdlet attribute is declared. Support for transactions was introduced
in Windows PowerShell 2.0. For more information about transactions, see How to
Support Transactions.
Windows PowerShell supports cmdlets that are derived from the following two
base classes.
Most cmdlets are based on .NET classes that derive from
the System.Management.Automation.Cmdlet base class. Deriving
from this class allows a cmdlet to use the minimum set of
dependencies on the Windows PowerShell runtime. This has two
benefits. The first benefit is that the cmdlet objects are smaller, and
you are less likely to be affected by changes to the PowerShell
runtime. The second benefit is that, if you have to, you can directly
create an instance of the cmdlet object and then invoke it directly
instead of invoking it through the PowerShell runtime.
In general, unless you need the extended access to the PowerShell runtime, you
should derive from the System.Management.Automation.Cmdlet class. However,
the PowerShell runtime has extensive logging capabilities for the execution of
cmdlets. If your auditing model depends on this logging, you can prevent the
execution of your cmdlet from within another cmdlet by deriving from
the System.Management.Automation.PSCmdlet class.
Cmdlet Attributes
PowerShell defines several .NET attributes that are used to manage cmdlets and
to specify common functionality that is provided by PowerShell and that might
be required by the cmdlet. For example, attributes are used to designate a class
as a cmdlet, to specify the parameters of the cmdlet, and to request the
validation of input so that cmdlet developers do not have to implement that
functionality in their cmdlet code. For more information about attributes,
see PowerShell Attributes.
Cmdlet Names
These names are specified when the .NET class is declared as a cmdlet. For
more information about how to declare a .NET class as a cmdlet, see Cmdlet
Attribute Declaration.
Adv Cmdlets
1 Get-Unique Cmdlet
Get-Unique cmdlet can be used to get the unique objects from a sorted list o
objects.
In this example, we're see the Get-Unique cmdlet in action.
2
Group-Object Cmdlet
Example program to showcase Group-Object Cmdlet.
3 Measure-Object Cmdlet
Measure-Object cmdlet can be used to get the properties of the passed outpu
such as min, max, size, count, line etc.
4 Compare-Object Cmdlet
Compare-Object cmdlet can be used to compare two objects.
5 Format-List Cmdlet
Format-List cmdlet can be used to formats the output as a list of properties where
a property appears on a new line.
6 Format-Wide Cmdlet
Where-Object cmdlet can be used to select objects having particular property
values from the collection of objects that are passed to it.
7
Where-Object Cmdlet
Where-Object cmdlet can be used to select objects having particular property
values from the collection of objects that are passed to it.
8 Get-ChildItem Cmdlet
Get-ChildItem cmdlet can be used to get the items or child items in one or more
specific locations.
9 ForEach-Object Cmdlet
ForEach-Object cmdlet can be used to perform operations on each object of a
collection of objects..
10 Start-Sleep Cmdlet
Start-Sleep cmdlet suspends the activity in a script or session for the particula
period of time.
11 Read-Host Cmdlet
Read-Host cmdlet is used to read from the console.
In these example, we're see the Read-Host cmdlet in action.
12 Select-Object Cmdlet
Select-Object cmdlet is used to select object or its properties.
13 Sort-Object Cmdlet
Sort-Object cmdlet is used to sort object by its properties.
14 Write-Warning Cmdlet
Write-Warning cmdlet is used to write warning messages.
15 Write-Host Cmdlet
Write-Host cmdlet is used to write customized messages.
16 Invoke-Item Cmdlet
Invoke-Item cmdlet is used to perform a default action on specified item
17 Invoke-Expression Cmdlet
Invoke-Expression cmdlet is used to perform a command or expression on loca
computer.
18 Measure-Command Cmdlet
Measure-Command cmdlet is used to meaure the time taken by script o
command.
19 Invoke-History Cmdlet
Invoke-History cmdlet is used to run the command from the current session
which are already run.
20 Add-History Cmdlet
Add-History cmdlet is used to add commands in current history.
21 Get-History Cmdlet
Get-History cmdlet is used to get commands run in current session.
22 Get-Culture Cmdlet
Get-Culture cmdlet is used to get current culture set in windows..
Operator Description
(b) Operators
An operator is a character that can be used in the commands or
expressions. It tells the compiler or interpreter to perform the specific
operations and produce the final result.
Arithmetic Operators
Arithmetic operators are used to perform numeric calculations. The
operators that are available are available to us in PowerShell are as
follows:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Remainder: %
- Shift left: -shl
- Shift right: -shr
As well as its use in numeric calculations, the addition operator may
also be used with strings, arrays, and hashtables, and the
multiplication operator may also be used with strings and arrays.
For example
The following scripts demonstrates the arithmetic operators.
> $a = 10
> $b = 20
> $c = 25
> $d = 25
> $a + $b
30
> $a - $b
-10
> $a * $b
200
> $b / $a
2
> $b % $a
0
Assignment Operators
Assignment operators are used to give values to variables. The
assignment operators that are available are as follows:
- Assign: =
- Add and assign: +=
- Subtract and assign: -=
- Multiply and assign: *=
- Divide and assign: /=
- Modulus and assign: %=
As with the arithmetic operators, add and assign may be used with
strings, arrays, and hash tables. Multiply and assign may be used
with strings and arrays.
Example
The following scripts demonstrates the assignment operators.
> $a = 10
> $b = 20
> $c = $a + $b
> $c
30
> $c += $a
> $c
40
> $c -= $a
> $c
30
Comparison Operators
Comparison operators are used for comparing two mathematical
expressions which results in true, false or unknown. PowerShell has a
wide variety of comparison operators which are as follows:
- Equal to and not equal to: -eq and -ne
- Like and not like: -like and -notlike
- Greater than and greater than or equal to: -gt and -ge
- Less than and less than or equal to: -lt and -le
- Contains and not contains: -contains and -notcontains
- In and not in: -in and -notin
Example
The following scripts demonstrates the comparison operators.
> $a = 10
> $b = 20
> $a -eq $b
False
> $a -ne $b
True
> $b -gt $a
True
> $b -ge $a
True
> $b -lt $a
False
> $b -le $a
False
> $a = "mahesh"
> $b = "suresh"
> $a = 'abc'
> $b = 'abc'
> $b -contains $a
True
> $b -notContains $a
False
Logical Operators
The logical operators are used in PowerShell to connect expressions or
statements together to form a single expression. Those expressions
which contain the logical operators usually result in the Boolean
values True or False.
Operator Description Example
Example
The following scripts demonstrates the logical operators.
> $a = 10
> $b = 20
> $a -AND $b
True
> $a -OR $b
True
Redirection Operators
The redirection operators are used in PowerShell to redirect the
output of one command as an input to another command. This
operator describes how to redirect the output from the PowerShell to
the text files.
Operator Description Example
Example
The following scripts demonstrates the miscellaneous operators.
> $i = 1
> $i++
> $i
2
foreach
The foreach loop executes against each element of a collection using
the following
notation:
For example:
the foreach loop may be used to iterate through each of the processes
returned by Get-Process:
for
The for loop is typically used to step through a collection using the
following notation:
example:
$processes = Get-Process
for ($i = 0; $i -lt $processes.Count; $i++) {
Write-Host $processes[$i].Name
}
do {
Write-Host "Waiting for boot"
Start-Sleep -Seconds 5
} until (Test-Connection 'SomeComputer' -Quiet -Count 1)
The do while loop is more suitable for exit conditions that are
negative. For example, a loop might wait for a remote computer to stop
responding to a ping:
do {
Write-Host "Waiting for shutdown"
Start-Sleep -Seconds 5
} while (Test-Connection 'SomeComputer' -Quiet -Count 1)
while
As the condition for a while loop comes first, the body of the loop will
only execute if the condition evaluates to true:
while (<condition>) {
<body-statements>
}
1. Stream Control
2. Parameter Validation
3. Pipeline Binding
4. Safeguards
Stream Control
1. Output / Success
2. Error
3. Warning
4. Verbose
5. Debug
Depending on the context we can leverage inbuilt cmdlets to write to a specific
stream, for example if we want to write to the verbose stream, we can use
the Write-Verbose cmdlet and so on.
However, just using the right cmdlet is not enough as we can observe in figure
1.
In order for the -Verbose switch to work we need to change our function and
add CmdletBinding as shown in the following example:
Function Do-SomethingRegular{
[CmdletBinding()]
param(
[String]$Message
)
Write-Verbose "We are going to write the message by the User"
Write-Output $Message
}
Do-SomethingRegular -Message "Hi Mom" -Verbose
Next, we look at a more complex example which involves the error stream. We
first need to define the difference between terminating and non-terminating
errors:
A non-terminating error is less serious and will not result in halting the
execution of the program.
But what if we wanted to terminate the script as soon as we encounter the non-
terminating error?
The solution is to modify the value of ErrorActionPreference variable to “Stop”.
However, changing this variable will impact all the other scripts on the system as
well as this is a global variable. The solution is to use the -ErrorAction switch as
shown in figure 4 and tell PowerShell engine to treat our script as if the
“ErrorActionPreference” variable is set to stop. Again, the reason we
have ErrorAction switch available is that we are using advanced functions.
Fig. 4: The ErrorAction switch in combination with the “Stop” option leads to
PowerShell terminating execution when encountering an error
Parameter Validation
Functions are not very useful unless they can accept parameters. Helped
functions are a different story though however our focus is on regular functions.
2. ValidateScript
3. ValidatePattern
Function Do-SomethingRegular {
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidatePattern('\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(.|$)){4}\b')]
[String] $MachineName
)
Get-CimInstance -ComputerName $MachineName -ClassName win32_Process
}
Do-SomethingRegular -MachineName 127.0.01.1
4. ValidateSet
Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory)]
[ValidateSet('Mom','Dad')]
[String] $Parent
)
Write-Output "Hello " $Parent
}
Do-SomethingRegular -Parent
Pipeline Binding
PowerShell engine binds the pipeline input “by value” or “by property”. Advanced
functions allow us to specify which parameters can accept pipeline input and how
binding should take place.
Let’s take a simple example where we are accepting the pipeline input byValue:
Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory,valueFromPipeline)]
[String] $name
)
Write-Output "You Entered $name"
}
"Sonny"|Do-SomethingRegular
Figure 9 shows that a string object is passed to our function and since the
function has a parameter accepting value from the pipeline, the functions
executed without any errors.
Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory,valueFromPipelineByProperty)]
[String] $name
)
Write-Output "You Entered $name"
}
$MyNewObject = [PSCustomObject]@{name = 'Sonny'; age = 21}
$MyNewObject | Do-SomethingRegular
As shown in figure 10, we created an object with a property name matching the
name of our parameter. When this object is passed in the pipeline the
PowerShell engine binds the property with the parameters as they have
matching name.
Fig. 10: Passing a single property of an object as parameter value to a function
through the pipeline
Let’s complicate our example by passing more than one object in the pipeline.
Since we are dealing with multiple objects, we need to utilize Input Processing
methods. Input processing methods are also known as
the BEGIN, PROCESS and END block. A good PowerShell programmer will always
use them when writing an advanced function.
As we can observe in figure 11, even with multiple objects the binding follows
the same principle as our previous example:
Function Do-SomethingRegular{
[CmdletBinding()]
Param(
[Parameter(Mandatory,valueFromPipelineByPropertyName)]
[String] $name
)
process{
Write-Output "You Entered $name"
}
}
Safeguards
WhatIf
Confirm
WhatIf
Function Delete-Windows{
# First we're adding the “SupportsShouldProcess” argument to CmdletBinding
[CmdletBinding(SupportsShouldProcess)]
param(
)
# Then, we're capturing the Boolean value returned by
“$PSCmdlet.ShouldProcess("")”, If TRUE it means user has not selected whatif
option
if($PSCmdlet.ShouldProcess("Meow")){
Write-Host "WhatIf flag not set, delete
windows"
}
else{
Write-Host "WhatIf flag set, do not delete
windows or real"
}
}
Confirm
“Low”
“Medium”
“High”
We can also set it to “None” but that will just disable it.
Function Delete-Windows{
[CmdletBinding(SupportsShouldProcess, ConfirmImpact =
"Medium")]
param(
)
if($PSCmdlet.ShouldProcess("Meow"){
Write-Host "Delete Windows"
}
}
Error handling with PowerShell helps ensure that an unexpected exception does
not let a script continue to cause issues. Let’s take a look at a script that will
make sure only cool people have access to all the cool stuff. (
Foreach($Person in $GroupMembership){
}
}
Works great! However, Kris Powell has found out about the cool list, and in
anger at being left off the list, he performs an action that proves we are right to
keep him out. He deletes CoolPeople.csv.
Exceptions
ErrorAction Stop
You can also set the default action of all errors to stop by setting the
variable $ErrorActionPreference = "Stop".
Try/Catch/Finally
Try {
$UpdatedCoolList = Get-Content \\FileShare\Location\CoolPeople.csv -
ErrorAction Stop
Catch {
Break
In this script-block, we captured the exception and put it in a log file. Break was
used to exit the script so it would not continue. If we had left the catch block
empty it would absorb the error and continue the script.
The last piece of the error handling with a Try/Catch/Finally block is the Finally.
This is used to provide actions that will always run before exiting the script (or
continuing on). This is mostly used for clean up. You can use it to close database
connections, remove files, or close file locks. Finally allows you to revert any
changes done as a result of the script whether an exception is encountered or
not.
Python - OS Module
We must first change the current working directory to a newly created one
before doing any operations in it. This is done using the chdir() function. The
following change current working directory to C:\MyPythonProject.
Removing a Directory
The listdir() function returns the list of all files and directories in the specified
directory.
The http or Hyper Text Transfer Protocol works on client server model. Usually
the web browser is the client and the computer hosting the website is the server.
IN python we use the requests module for creating the http requests. It is a very
powerful module which can handle many aspects of http communication beyond
the simple request and response data. It can handle authentication,
compression/decompression, chunked requests etc.
1. Grequests
GRequests allows you to use Requests with Gevent to make asynchronous HTTP
Requests easily.
Command: pip install grequests
import grequests urls = [ ‘http://www.heroku.com’,
‘http://python-tablib.org’,
‘http://httpbin.org’,
‘http://python-requests.org’,
‘https://yeahhub.com/’
]
2. httplib2
– Comprehensive HTTP client library. The Hypertext Transfer Protocol (HTTP) is
an application protocol for distributed, collaborative, hypermedia information
systems. HTTP is the foundation of data communication for the World Wide Web.
Python httplib2 module provides methods for accessing Web resources via HTTP.
It supports many features, such as HTTP and HTTPS, authentication, caching,
redirects, and compression. Httplib2 is a comprehensive HTTP client library,
httplib2.py supports many features left out of other HTTP libraries. HTTPS
support is only available if the socket module was compiled with SSL support.
Command: pip install httplib2
#!/usr/bin/python3
import httplib2
http = httplib2.Http()
content = http.request(“https://www.yeahhub.com”)[1]
(content.decode())
#!/usr/bin/env python
from twisted.internet.task import react
from _utils import print_response
import treq
def main(reactor, *args):
d = treq.get(‘http://httpbin.org/get’)
d.addCallback(print_response)
return d
react(main, [])
Urllib3 is a powerful, sanity-friendly HTTP client for Python. Much of the Python
ecosystem already uses urllib3 and you should too. urllib3 brings many critical
features that are missing from the Python standard libraries:
Thread safety.
Connection pooling.
Client-side SSL/TLS verification.
File uploads with multipart encoding.
Helpers for retrying requests and dealing with HTTP redirects.
Support for gzip and deflate encoding.
Proxy support for HTTP and SOCKS. 100% test coverage.
Cp:-The cp program copies files and directories. In its simplest form, it copies a
single file. It can also be used to copy multiple files (and/or directories) to a
different directory.
Mkdir:-The mkdir command is used to create directories. To use it, you simply
type
One Value to Multiple Variables:-And you can assign the same value to
multiple variables in one line.
Whitelisting tackles the same challenges as blacklisting but uses the opposite
approach. Instead of creating a list of threats, you create a list of permitted
entities and block everything else. It’s based on trust, and the default is to deny
anything new unless it’s proven to be acceptable. This results in a much stricter
approach to access control. It’s analogous to denying everyone access to your
office building unless they can pass a background check and have the credentials
to prove that they did.If a firewall only allows particular IP addresses to access a
network, for instance, it’s using the whitelisting approach.
we will discuss on how to get Geolocation when you enter any location name and
its gives all the useful information such as postal code, city, state, country etc.
with the latitudes and the longitudes (the specific coordinates) and vice-versa in
which we provide the coordinates to get the location name. This can be done
using the GeoPy library in python. This library isn’t built into python and hence
needs to be installed explicitly.
Method 2:
Getting location name from latitude and longitude In this method all the things
are same as the above, the only difference is instead of using the geocode
function we will now use the reverse() method which accepts the coordinates
(latitude and longitude) as the argument, this method gives the address after
providing it with the coordinates.
Syntax:
reverse(latitude,longitude)
Approach
Import module
Call nominatim tool
Pass latitude and longitude to reverse()
Print location name
# importing modules
from geopy.geocoders import Nominatim
# calling the nominatim tool
geoLoc = Nominatim(user_agent="GetLoc")
# passing the coordinates
locname = geoLoc.reverse("26.7674446, 81.109758")
# printing the address/location name
print(locname.address)
If Statement
syntax:
if expression
Statement
num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
5 is a positive number.
This statement is true.
are specified to be executed. When the condition is true, the statement inside
the if block is executed; if the condition is false, the statement outside the if
block is executed.
syntax:
if condition :
#Will executes this block if the condition is true
else :
#Will executes this block if the condition is false
num = 5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
output : Positive or Zero
If…Elif..else Statement
In this case, the If condition is evaluated first. If it is false, the Elif statement will
syntax:
if condition :
Body of if
elif condition :
Body of elif
else:
Body of elseExample for better understanding:
num = 7
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
output: Positive number
Nested IF Statement
If statement. This is used when a variable must be processed more than once.
If, If-else, and If…elif…else statements can be used in the program. In Nested If
syntax:
if (condition1):
#Executes if condition 1 is true
if (condition 2):
#Executes if condition 2 is true
#Condition 2 ends here
#Condition 1 ends here
Short Hand if statement is used when only one statement needs to be executed
inside the if block. This statement can be mentioned in the same line which
if condition: statement
i=15
# One line if statement
if i>11 : print (“i is greater than 11″)
The output of the program : “i is greater than 11.”
It is used to mention If-else statements in one line in which there is only one
statement to execute in both if and else blocks. In simple words, If you have
only one statement to execute, one for if, and one for else, you can put it all on
a=3
b=5
print("A") if a > b else print("B")
output: B
The default editor that comes with the UNIX operating system is called vi
(visual editor). Using vi editor, we can edit an existing file or create a new file
from scratch. we can also use this editor to just read a text file.
Syntax:
vi filename
There are several shells are available for Linux systems like –
BASH (Bourne Again SHell) – It is most widely used shell in
Linux systems. It is used as default login shell in Linux systems
and in macOS. It can also be installed on Windows OS.
CSH (C SHell) – The C shell’s syntax and usage are very similar
to the C programming language.
KSH (Korn SHell) – The Korn Shell also was the base for the
POSIX Shell standard specifications etc.
Each shell does the same job but understand different commands and
provide different built in functions.
Why do we need shell scripts
There are many reasons to write shell scripts –
To avoid repetitive work and automation
System admins use shell scripting for routine backups
System monitoring
Adding new functionality to the shell etc.
Advantages of shell scripts
The command and syntax are exactly the same as those
directly entered in command line, so programmer do not need
to switch to entirely different syntax
Writing shell scripts are much quicker
Quick start
Interactive debugging etc.
Disadvantages of shell scripts
Prone to costly errors, a single mistake can change the
command which might be harmful
Slow execution speed
Design flaws within the language syntax or implementation
Not well suited for large and complex task
Provide minimal data structure unlike other scripting
languages. etc
EXPLAIN THE THE FILE SYSTEM TREE AND ITS NAVIGATION WITH
SHELL COMMANDS? (5 MARKS)
A file system is a logical collection of files on a partition or disk. A partition is a
container for information and can span an entire hard drive if desired.
Your hard drive can have various partitions which usually contain only one file
system, such as one file system housing the /file system or another containing
the / home file system.
One file system per partition allows for the logical maintenance and
management of differing file systems.
Everything in Unix is considered to be a file, including physical devices such as
DVD-ROMs, USB devices, and floppy drives the files on a Linux system are
arranged in what is called a hierarchical directory structure. This means that
they are organized in a tree-like pattern of directories (called folders in other
systems), which may contain files and subdirectories. The first directory in the
file system is called the root directory. The root directory contains files and
subdirectories, which contain more files and subdirectories
Navigation commands