0% found this document useful (0 votes)
115 views119 pages

Python For Beginners

This document provides an introduction and overview of the Python programming language. It discusses Python's timeline and conception in 1989. It outlines Python's key features such as simple syntax, high-level coding, object-oriented and procedural programming, being free and open source, and its extensive standard libraries. The document also discusses popular uses of Python including for games, image processing, science, web development, and more. It provides instructions on getting started with Python and covers basic syntax concepts.
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)
115 views119 pages

Python For Beginners

This document provides an introduction and overview of the Python programming language. It discusses Python's timeline and conception in 1989. It outlines Python's key features such as simple syntax, high-level coding, object-oriented and procedural programming, being free and open source, and its extensive standard libraries. The document also discusses popular uses of Python including for games, image processing, science, web development, and more. It provides instructions on getting started with Python and covers basic syntax concepts.
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
You are on page 1/ 119

Python for Beginners

Python Programming Language


Introduction

2
Python Timeline
• Python is an Interpreted, Object Oriented, High Level Language.
• Python programs are executed by an interpreter.
• Python conceived by Guido van Rossum in the Netherlands.

• Implementation Start: December 1989


• Python Beta 0.9.0: 1991
• Python 1.0: January 1994
• Python 2.0: October 2000
• Python 3.0: December 2008

3
Python Features….1
• Simple Syntax:
• almost like reading English (but very strict English)
• Helps focus on the solution to the problem rather than the syntax.
• High-level Language
• When you write programs in Python, you never need to bother about low-level details such as
managing the memory used by your program.
• Object Oriented
• Python supports procedure-oriented programming as well as object-oriented programming.
• In procedure-oriented languages, the program is built around procedures or functions which
are nothing but reusable pieces of programs.
• In object-oriented languages, the program is built around objects which combine data and
functionality.

4
Python Features….2
• Free and Open Source
• Python is an example of a FLOSS (Free/Libre and Open Source Software).
• FLOSS is based on the concept of a community which shares knowledge.
• In simple terms, you can freely distribute copies of this software, read the software's source
code, make changes to it, use pieces of it in new free programs.

• Extensive Libraries
• The Python Standard Library is huge indeed. It can help you do various things involving
regular expressions, documentation generation, unit testing, threading, databases, web
browsers, cryptography, Statistical Extensions (Pandas, NumPy), GUI using Tk etc.
• Besides the standard library, there are various other community developed high-quality
libraries such as the Imaging Library which is an amazingly simple image manipulation
library, and can be used to develop Games.

5
Where Python is Used.
• Games
• Python has various modules, libraries and platforms that support development of games.
• PySoy is a 3D game engine supporting Python 3, and PyGame provides functionality and a library for
game development.
• There have been numerous games built using Python including Civilization-IV, Disney’s Toontown
Online, Vega Strike
• Image Processing and Graphic Design Applications
• Python has been used to make 2D imaging software such as Inkscape, GIMP, Paint Shop Pro and Scribus.
• Further, 3D animation packages, like Blender, 3ds Max, Cinema 4D, Houdini, Lightwave and Maya, also
use Python in variable proportions.
• Scientific and Computational Applications:
• scientific data. 3D modeling software, such as FreeCAD
• Stock market analysis, Weather Forecasting
• Web Frameworks and Web Applications
• web-frameworks including CherryPy, Django, TurboGears, Bottle, Flask etc
• simplify tasks related to content management, interaction with database and interfacing with different
internet protocols such as HTTP, SMTP, XML-RPC, FTP and POP.
• Embedded Test Automation
• More Python Success stories at https://www.python.org/about/success/ 6
Getting Python
• https://www.python.org/downloads/
• https://www.python.org/doc/

7
Python Execution Platforms
• Python executables are available for Unix/Linux, Windows/Cygwin and Mac OS.
• Can be downloaded from www.python.org

• Cygwin can be downloaded from https://www.cygwin.com

• Anaconda distribution.

8
Windows IDLE Shell

9
Basic Syntax

10
Single Line Instructions
• Useful to use Shell as a Calculator

11
Python Identifier
• A Python Identifier is a name used to identify a Variable, function, class, module or other
object.

• Starts with Alphabet.


• Should not start with Numbers.
• Should not have a Special Character like $, @, #
• underscores_ can be used.
• Python Language Keywords cannot be used as Identifier Names.
• Python Identifiers can Case Sensitive.

• Good Programmers choose Identifier Names that are meaningful to the context and
logic of the Program.

12
Python Identifier..
• Open a Python Shell, and key in the below variable assignment statements.

13
Reserved Words
• Python has the following keywords or reserved words; they cannot be used as identifiers.
• These keywords could be built-in Operators , block markers, control markers .

• and as assert break class continue


• def del elif else except False
• finally for from global if import
• in is lambda None nonlocal not
• or pass print raise return True
• try while with yield

14
Python Script
• A Statement is an instruction that the Python interpreter can execute.
• When you type a statement on the command line, Python executes it and displays the result, if
there is one.

• A script is a sequence of statements.


• If there is more than one statement, the results appear one at a time, as and when the
statements are executed by the Interpreter.

• Execution can be done in few ways:


• Executing the Script from the “RUN” Menu Options of the IDE.

• By Passing the Script as an Argument to the Interpreter Command. (Linux, DosPrompt)

• Convert the Script into a Executable, by Embedding the Interpreter Path. (Linux)

15
First Script
• Create first.py as below

16
print: Diff b/n Python 2.x and 3.x
• Python 2.x • Python 3.x.
• Backward Compatible to 2.x

17
Indentation Example
#!/usr/bin/python file.close()
import sys file_name = raw_input("Enter filename: ")

print("' When finished“) if len(file_name) == 0:


print("please enter something“)
while file_text != file_finish: sys.exit()
file_text = raw_input("Enter text: ")
if file_text == file_finish: file_text = file.read()
# close the file file.close()
file.close print(file_text)
break
file.write(file_text)
file.write("\n")
18
Multi Line Statements
• Statements in Python typically end with a new line.
• \ used to denote line continuation.

19
Quotations
• Python accepts ('), (") and (''' or """) quotes to denote string literals, as long as the same
type of quote starts and ends the string.
• The triple quotes are used to span the string across multiple lines.

20
Multiple Statements on Single Line
• ;

21
Variable Types

22
Assignment of Value
• No Separate Declaration Phase.
• Memory Allocated as soon as Definition.
• =

23
Multiple Assignment
• Can assign a single value to several variables simultaneously.
• id(var), gives unique number of the object.

24
Multiple Assignment
• Can assign multiple objects to multiple variables

25
Standard Data Types
• The data stored in memory can be of many types.

• Python has five standard data types


• Numbers
• String
• List
• Tuple
• Dictionary

26
Numbers & Types
• Number data types store numeric values.
• Number objects are created when you assign a value to them.

• Python supports four different numerical types −


• int (signed integers)
• long (long integers, they can also be represented in
octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)

27
Strings
• Strings in Python are identified as a contiguous set of characters represented in the
quotation marks.
• Not-Mutable.

28
List
• Sequence of Items, [… , … , ….]
• Different data types, Individual Access, Mutable.

29
Tuple
• Sequence of Items, (… , … , ….)
• Different data types, Individual Read Access, Not-Mutable.

30
Dictionary
• Dictionary is a Built-in datatypes , which defines 1:1 relationships between keys and
values.
• Each key is separated from its value by a colon (key:value).
• Dictionaries are enclosed by curly braces { } and values can be assigned and accessed
using square braces [ ]

31
Data Type Conversion
• Python provides a collection of built-in functions that convert values from one type to
another.

32
Functions

33
Function Syntax
• In the context of programming, a function is a named sequence of statements that
performs a desired operation.
• This operation is specified in a function definition.

34
Function Interpretation
• Defining a function only gives it a name, specifies the parameters that are to be included in
the function and structures the blocks of code.

• The statements inside the function do not get interpreted until the function is called, and
the function definition generates no output.

• The function definition has to be parsed/initialized before the first time it is called.

• By default, parameters have a positional behavior and you need to pass arguments in the
same order that they were defined.

35
A Simple Function
• Create a Python Script like below and execute.

36
Keyboard Input 2.x Version

37
Keyboard Input 3.x Version

38
KB input. Diff b/n 2.x & 3.x
• In 2.x:
• Inbuilt function raw_input() is used to accept user input and returns a string.
• Inbuilt function input() is used to accept user input as an Integer.

• In 3.x
• raw_input() of 2.x is removed.
• input() function changed to accept user input, as a String, like raw_input of 2.x.
• In order to accept integer inputs, int(..) must be used for Type Conversion.

39
Keyboard Input. Example

40
Parameters & Arguments
• Below function takes a single argument and assigns it to a parameter named par_name

41
Return Values
• The statement return [expression] exits a function, optionally passing back an expression
to the caller.
• A return statement with no arguments is the same as return None.

• >>> def asum(n11,n12):


• fsum = n11+n12
• return fsum

• >>> fs = asum(20,20)+2

42
Function Argument Types
• You can call a function by using the following types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

43
Checking Type of Variable
• What happens if we call factorial and give it 1.5 as an argument?
• Logically Wrong…Error expected…
• We can use the built-in function isinstance to verify the type of the argument.
• This program demonstrates a pattern called guardian.
• The first two conditionals act as guardians, protecting the code that follows from values
that might cause an error.

44
print(..) method

45
Escape Sequences
• Escape sequences represent non-printable and special characters in character and literal
strings. e.g. \r, \n, \t
• They allow users to communicate with a display device or printer by sending non-
graphical control characters to specify actions like carriage returns.
• An escape sequence refers to a combination of characters beginning with a back slash (\)
followed by letters or digits.

46
Operators

47
Operators & Operands
• Operators are special symbols that represent specific type of computations.
• The values the operator uses are called operands.
• Operators are the constructs which can manipulate the value of operands.

• + for addition, - for subtraction, * for multiplication, ** for exponentiation.


• 20+32 , hour-1 , hour*60+minute , (5+9)*(15-7), 5**2

• When a variable name appears in the place of an operand, it is replaced with its value
before the operation is performed.

• Parenthesis used for grouping.

48
Expression
• An expression is a combination of either/all of values, variables, and operators.

• The left-hand side of an assignment statement has to be a variable name, not an


expression.
• So, the following is illegal: minute+1 = hour.

49
Types of Operators
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators

50
Arithmetic Operators

Operator Description
+ Addition result = a + b (sum of operands)
- Subtraction result = a - b (difference of operands)
*
result = a * b (product of operands)
Multiplication
/ Division result = a / b (result of the division, float)
% Modulus result = a % b (remainder of the division)
** Exponent result = a ** b ( a to the power of b)
// result = a // b (floor division, no Decimal, Quotient)

51
Relational operators
• These operators compare the values on either sides of them and decide the relation among
them.
Operator Description
== if ( a is equal to b) then condition is True, else False

!= if ( a is not equal to b) then condition is True, else False


<> if ( a is not equal to b) then condition is True, else False

> if ( a is greater than b) then condition is True, else False

< if ( a is lesser than b) then condition is True, else False

>= if ( a is greater or equal to b) then condition is True, else False

<= if ( a is lesser or equal to b) then condition is True, else False


52
Relational operators
#!/usr/bin/python if ( a <> b ): a = 5; b = 20;
print "a not equal b"
a = 21; b = 10 else: if ( a <= b ):
print "a equal b" print "a either less than or equal to b"
if ( a == b ): else:
print "a equals b" if ( a < b ): print "a neither less than nor equal to b"
else: print "a less than b"
print "a not equal b" else: if ( a >= b ):
print "a not less than b" print “a either greater than or equal to b"
if ( a != b ): else:
print "a not equal b" if ( a > b ): print “a neither greater than nor equal to b"
else: print "a greater than b"
print "a equals b" else:
print "a not greater than b"

53
Assignment Operators

Operator Description
= result = a ; result = a+b
+= result += a; same as result = result + a
-= result -= a; same as result = result – a
*= result *= a; same as result = result * a
/= result /= a; same as result = result / a
%= result %= a; same as result = result % a
**= result ** = a; same as result = result ** a
//= result //= a; same as result = result // a

54
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.

Assume if a = 0x3C; and b = 0xD;


Now in binary format they will be as follows −
a= 0011 1100
b= 0000 1101

a&b = 0000 1100 ## AND


a|b = 0011 1101 ## OR
a^b = 0011 0001 ## XOR
~a = 1100 0011 ## NOT
a <<= 1 0111 1000 ## left shift by 1
a >>= 1 0001 1110 ## right shift by 1
55
Bitwise Operators

Operator Description
& Binary AND Operator copies a bit to the result if it exists in both
operands
| Binary OR It copies a bit if it exists in either operand.
^ Binary XOR It copies the bit if it is set in one operand but not
both.
~ Binary Ones Complement It is unary and has the effect of 'flipping' bits.
<< Binary Left Shift The left operands value is moved left by the number
of bits specified by the right operand.
>> Binary Right Shift The left operands value is moved right by the number
of bits specified by the right operand.

56
Logical Operators
• Three logical operators: and, or, and not.
• the operands of the logical operators should be Boolean or relational expressions.
• Any nonzero number is interpreted as “True.”

57
Membership Operators
• Python’s membership operators test for membership in a sequence, such as strings, lists,
or tuples.

Operator Description
in Evaluates to True if it finds a variable in a specified sequence and false
otherwise.
not in Evaluates to true if it does not finds a variable in the specified
sequence and false otherwise.

58
Membership Operators.

59
Identity Operators
• Identity operators compare the memory locations of two objects.

Operator Description
is Evaluates to true if the variables on either side of the
operator point to the same object and false otherwise.
is not Evaluates to false if the variables on either side of the
operator point to the same object and true otherwise.

60
Operators Precedence
• When more than one operator appears in an expression, the order of evaluation depends
on the rules of precedence.
• The acronym PEDMAS is a useful way to remember the order for most frequently used
operations:
• Parentheses have the highest precedence
• Exponentiation
• Division and Multiplication have the same precedence
• Addition and Subtraction, also have the same precedence
• Operators with the same precedence are evaluated from left to right.
• Evaluate below & discuss the result
• (5+9)*(15-7), (1+1)**(5*2), 2**1+1, 3*1**3,
• 2/3-1, 59*100/60

61
Overall Operator Precedence
•Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators 62
Decision Making

63
Decision Making
• Conditional statements give us the ability to check conditions and change the behavior of
the program accordingly.
• Decision structures evaluate multiple expressions which produce TRUE or FALSE as
outcome. You need to determine which action to take and which statements to execute if
outcome is TRUE or FALSE otherwise.

64
IF, IF..ELSE, IF..ELIF..ELSE

65
Nested IF
• There may be a situation when you want to check for another condition after a condition
resolves to true.
• In such a situation, you can use the nested if construct.

66
Lab Work…
#!/usr/bin/python var3 = 75 var4 = 65
if var3 >= 70: if var4 >= 40:
var1 = 45 print "var3 distinction" if var4 >= 70:
if var1 >= 40: elif var3 >= 60: print "var4 distinction"
print "var1 Pass" print "var3 first class" elif var4 >= 60:
elif var3 >= 40: print "var4 first class"
var2 = 35 print "var3 pass class" else:
if var2 >= 40: else: print "var4 pass class"
print "var2 Pass" print "var3 fail" else:
else: print "var4 fail"
print "var2 Fail"

67
Iteration
• In general, statements are executed sequentially:
• The first statement in a function is executed first, followed by the second, and so on.
• There may be a situation when you need to execute a block of code several number of
times.
• A loop statement allows us to execute a statement or group of statements multiple times.
• Each pass through the loop is called a Iteration.

68
While Loop
• Condition of an Expression is checked at the beginning of every Iteration.
• Loop may not execute at all.

• count = 0
• while (count < 9):
• print('The count is:', count)
• count = count + 1

• print("The End!”)

69
While.. Else
The else part is executed if the condition in the while loop evaluates to False.

counter = 0

while counter < 3:


print("Inside loop")
counter = counter + 1
else:
print("Inside else")

70
Other Flavors of While Loop.
Infinite While Loop Single Line While Loop

var = 1 flag = 1
while var == 1 : # constructs an infinite loop
print("Infinite Loop ", var) while (flag): print(“flag is true!”)

print("Will not Reach Here“) print("Will not Reach Here“)

71
Lab Work…
#!/usr/bin/python
counter = 0
count = 0
while counter < 3:
while (count < 9): print("Inside loop")
print 'The count is:', count counter = counter + 1
count = count + 1 else:
print("Inside else")
print "The End!"

72
For Loop
• The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects.
• Iterating over a sequence is called traversal.

for val in sequence:


Body of for

• val is the variable that takes the value of


the item inside the sequence on each
iteration, or index to an external sequence.

• Similar to While Loop, else can be used with for loop.

73
Lab Work…

74
break; Loop Control Statement
• The break statement terminates the loop
containing it.
• Control of the program flows to the statement
immediately after the body of the loop.

75
continue; Loop Control Statement
• The continue statement is used to skip the
rest of the code inside a loop for the
current iteration only.
• Loop does not terminate but continues on
with the next iteration.

76
Lab Work…

77
GoTo Next Subject

78
Working in Linux Platform

79
What is Linux
• A clone of Unix
• Developed in 1991 by Linus Torvalds, a Finnish graduate student
• Inspired by and replacement of Minix
• Linus' Minix became Linux
• Consist of
• Linux Kernel
• GNU (GNU is Not Unix) Software
• Software Package management
• Others

80
What is Linux
• Originally developed for 32-bit x86-based PC
• Ported to other architectures, eg.
• Alpha, VAX, PowerPC, IBM S/390, MIPS, IA-64
• PS2, TiVo, cellphones, watches, Nokia N810, NDS, routers, NAS, GPS, …

81
Linux Distributions
• > 300 Linux Distributions
• Slackware (one of the oldest, simple and stable distro.)
• Redhat
• RHEL (commercially support)
• Fedora (free)
• CentOS (free RHEL, based in England)
• SuSe ( based in German)
• Gentoo (Source code based)
• Debian (one of the few called GNU/Linux)
• Ubuntu (based in South Africa)
• Knoppix (first LiveCD distro.)
• …

82
Shell Intro
• A system program that allows a user to execute:
• shell functions (internal commands)
• other programs (external commands)
• shell scripts
• Linux/UNIX has a bunch of them, the most common are
• tcsh, an expanded version of csh (Bill Joy, Berkley, Sun)
• bash, one of the most popular and rich in functionality shells, an expansion of sh (AT&T Bell Labs)
• ksh, Korn Shell
• zhs
• ...

83
Shell
• The “Shell” is simply another program which provides a basic human-OS interface.
• Shells can run interactively or as a shell script
• Two main ‘flavors’ of Shells:
• Bourne created what is now known as the standard shell: “sh”, or “bourne shell”. It’s syntax
roughly resembles Pascal. It’s derivatives include “ksh” (“korn shell”) and now, the most widely
used, “bash” (“bourne shell”).
• One of the creators of the C language implemented the shell to have a “C-programming” like
syntax. This is called “csh” or “C-shell”. Today’s most widely used form is the very popular
“tcsh”.

84
Shell I/O
• Shell is a “power-user” interface, so the user interacts with the shell by typing in the
commands.
• The shell interprets the commands, that may produce some results, they go back to the
user and the control is given back to the user when a command completes (in general).
• In the case of external commands, shell executes actual programs that may call functions of
the OS kernel.
• These system commands are often wrapped around a so-called system calls, to ask the
kernel to perform an operation (usually privileged) on your behalf.

85
man
• Manual Pages
• The first command to remember
• Contains info about almost everything :-)
• other commands
• system calls
• c/library functions
• other utils, applications, configuration files
• % man vi

86
which
• Displays a path name of a command.
• Searches a path environmental variable for the command and displays the absolute path.
• To find which tcsh and bash are actually in use, type:
% which tcsh
% which bash
• % man which for more details

87
date
• Guess what :-)
• Displays dates in various formats
• % date
• % date -u
• in GMT
• % man date

88
cal
• Calendar • % cal current month
• for month • % cal 2 2000 Feb 2000, leap year
• entire year • % cal 2 2100 not a leap year
• Years range: 1 - 9999 • % cal 2 2400 leap year
• No year 0 • % cal 9 1752 11 days skipped
• Calendar was corrected in 1752 - • % cal 0 error
removed 11 days • % cal 2002 whole year

89
clear
• Clears the screen
• There’s an alias for it: Ctrl+L
• Example sequence:
• % cal
• % clear
• % cal
• Ctrl+L

90
sleep
• “Sleeping” is doing nothing for some time.
• Usually used for delays in shell scripts.
• % sleep 2 2 seconds pause

91
alias
• Defined a new name for a command
• % alias
• with no arguments lists currently active aliases
• % alias newcommand oldcommand
• defines a newcommand
• % alias cl=‘cal 2003’
• % cl

92
unalias
• Removes alias
• Requires an argument.
• % unalias cl

93
history
• Display a history of recently used • % !n
commands • repeat command n in the history
• % history • % !-1
• all commands in the history • repeat last command = !!
• % history 10 • % !-2
• last 10 • repeat second last command
• % history -r 10 • % !ca
• reverse order • repeat last command that begins with ‘ca’
• % !!
• repeat last command

94
exit / logout
• Exit from your login session.
• % exit
• % logout

95
shutdown
• Causes system to shutdown or reboot cleanly.
• May require superuser privileges
• % shutdown -h now - stop
• % shutdown -r now - reboot

96
Files

97
ls
• List directory contents • % ls -F
• Has whole bunch of options, see man ls for • append “/” to dirs and “*” to executables
details. • % ls -l
• % ls • long format
• all files except those starting with a “.” • % ls -al
• % ls -a • % ls -lt
• all • sort by modification time (latest - earliest)
• % ls -A • % ls -ltr
• all without “.” and “..” • reverse

98
cat
• Display and concatenate files.
• % cat
• Will read from STDIN and print to STDOT every line you enter.
• % cat file1 [file2] ...
• Will concatenate all files in one and print them to STDOUT
• % cat > filename
• Will take whatever you type from STDIN and will put it into the file filename
• To exit cat or cat > filename type Ctrl+D to indicate EOF (End of File).

99
more / less
• Pagers to display contents of large files page by page or scroll line by line up and down.
• Have a lot of viewing options and search capability.
• Interactive. To exit: ‘q’

100
less
• less ("less is more") a bit more smart than the more command
• to display contents of a file:
• % less filename
• To display line numbers:
• % less -N filename
• To display a prompt:
• % less -P"Press 'q' to quit" filename
• Combine the two:
• % less -NP"Blah-blah-blah" filename
• For more information:
• % man less

101
touch
• By touching a file you either create it if it did not exists (with 0 length).
• Or you update it’s last modification and access times.
• There are options to override the default behavior.
• % touch file
• % man touch

102
cp
• Copies files / directories.
• % cp [options] <source> <destination>
• % cp file1 file2
• % cp file1 [file2] … /directory
• Useful option: -i to prevent overwriting existing files and prompt the user to confirm.

103
mv
• Moves or renames files/directories.
• % mv <source> <destination>
• The <source> gets removed
• % mv file1 dir/
• % mv file1 file2
• rename
• % mv file1 file2 dir/
• % mv dir1 dir2

104
rm
• Removes file(s) and/or directories.
• % rm file1 [file2] ...
• % rm -r dir1 [dir2] ...
• % rm -r file1 dir1 dir2 file4 ...

105
find
• Looks up a file in a directory tree.
• % find . -name name
• % find . \(-name ‘w*’ -or -name ‘W*’ \)

106
mkdir
• Creates a directory.
• % mkdir newdir
• Often people make an alias of md for it.

107
cd
• Changes your current directory to a new one.
• % cd /some/other/dir
• Absolute path
• % cd subdir
• Assuming subdir is in the current directory.
• % cd
• Returns you to your home directory.

108
pwd
• Displays personal working directory, i.e. your current directory.
• % pwd

109
rmdir
• Removes a directory.
• % rmdir dirname
• Equivalent:
• % rm -r dirname

110
ln
• Symbolic link or a “shortcut” in M$ terminology.
• % ln –s <real-name> <fake-name>

111
chmod
• Changes file permissions
• Possible invocations
• % chmod 600 filename
• -rw------- 1 user group 2785 Feb 8 14:18 filename
(a bit not intuitive where 600 comes from)
• % chmod u+rw filename
(the same thing, more readable)
• For the assignment:
• % chmod u+x myshellscript
(mysshellscript is now executable)
• -rwx------ 1 user group 2785 Feb 8 14:18 myshellscript

112
Pipes
• What's a pipe?
• is a method of interprocess communication (IPC)
• in shells a '|' symbol used
• it means that the output of one program (on one side of a pipe) serves as an input for the
program on another end.
• a set of "piped" commands is often called a pipeline
• Why it's useful?
• Because by combining simple OS utilities one can easily solve more complex tasks

113
grep
• Searches its input for a pattern.
• The pattern can be a simple substring or a complex regular expression.
• If a line matches, it’s directed to STDOUT; otherwise, it’s discarded.
• % echo “blah-foo” | grep blah
• Will print the matching line
• % echo “blah-foo” | grep zee
• Will not.
• See a separate grep tutorial.

114
Basic Commands
• ls • which
• $ ls -l • $ which ls
• $ ls -a • whereis
• $ ls -la • $ whereis ls
• $ ls -l --sort=time
• $ ls -l --sort=size -r • locate
• $ locate stdio.h
• cd • $ locate iostream
• $ cd /usr/bin
• rpm
• pwd • $ rpm -q bash
• $ pwd • $ rpm -qa
• ~ • $ rpm -qa | sort | less
• $ cd ~ • find
• ~user • $ find / | grep stdio.h
• $ cd ~weesan • $ find /usr/include | grep stdio.h
• What will “cd ~/weesan” do?

115
Basic Commands
• echo • rm
• $ echo “Hello World” • $ rm foo
• $ echo -n “Hello World” • $ rm -rf foo
• cat • $ rm -i foo
• $ cat /etc/motd • $ rm -- -foo
• $ cat /proc/cpuinfo • chgrp
• cp • $ chgrp bar /home/foo
• $ cp foo bar • chsh
• $ cp -a foo bar • $ chsh foo

• mv • chfn
• $ mv foo bar • $ chfn foo

• mkdir • chown
• $ mkdir foo • $ chown -R foo:bar /home/foo

116
Basic Commands
• tar • Pipe
• $ tar cvfp lab1.tar lab1 • $ cal > foo
• gzip • $ cat /dev/zero > foo
• $ gzip -9 lab1.tar • $ cat < /etc/passwd
• $ who | cut -d’ ‘ -f1 | sort | uniq | wc –l
• untar & ungzip
• $ gzip -cd lab1.tar.gz | tar xvf – • backtick
• $ tar xvfz lab1.tar.gz • $ echo “The date is `date`”
• touch • $ echo `seq 1 10`
• $ touch foo • Hard, soft (symbolic) link
• $ cat /dev/null > foo • ln vmlinuz-2.6.24.4 vmlinuz
• ln -s firefox-2.0.0.3 firefox

117
VI Editor
• 2 modes • Delete
• dd (delete a line)
• Input mode • d10d (delete 10 lines)
• ESC to back to cmd mode • d$ (delete till end of line)
• Command mode • dG (delete till end of file)
• Cursor movement • x (current char.)
• h (left), j (down), k (up), l (right) • Paste
• ^f (page down) • p (paste after)
• ^b (page up) • P (paste before)
• ^ (first char.) • Undo
• $ (last char.) • u
• G (bottom page) • Search
• :1 (goto first line) • /
• Swtch to input mode • Save/Quit
• a (append) • :w (write)
• i (insert) • :q (quit)
• o (insert line after • :wq (write and quit)
• O (insert line before) • :q! (give up changes)

118
Thank You

119

You might also like