02 Sm1 Linux Cg

download 02 Sm1 Linux Cg

of 43

Transcript of 02 Sm1 Linux Cg

  • 7/27/2019 02 Sm1 Linux Cg

    1/43

    Linux 7.1-Coordinator Guide

    NIIT Linux 1

  • 7/27/2019 02 Sm1 Linux Cg

    2/43

    2 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    3/43

    RATIONALE

    Why This Module

    Linux is often considered an excellent, low-cost alternative to other expensive operating systems It has

    accelerated the free software movement in the industry The course starts with the history and thearchitecture of Linux operating system and covers advanced topics that ma!e a student a power user

    This module is very important for the learner as the fundamental commands li!e ls, cp, rm, and

    mkdir would "e later used in #$$ This module is important as the student needs to !now a"out

    creating and maintaining documents using the vieditor in Linux, as he would "e using it to type #$$

    programs

    Lina!e "ith #LT$ OO#s and %a&a

    The Linux module provides implementation of concepts covered in the %rogramming Logic and

    Techni&ues '%LT( module )hell scripts are used to demonstrate the se&uencing, decision, and iterationconstructs covered in the %LT module

    Linux provides a powerful platform for programming languages such as #$$ The Linux moduleprovides students with sufficient !nowledge to wor! comforta"ly on the Linux platform during the

    **%s+#$$ module

    The programming fundamentals covered in this module would help the learner understand o"ect-

    oriented programming The learner would "e a"le apply these concepts in #$$ and ava

    NIIT Linux .

  • 7/27/2019 02 Sm1 Linux Cg

    4/43

    O'%ECTI(E)

    The o"ective of this module is to familiari/e students with the Linux platform and provide sufficient

    !nowledge to ma!e them power users 0s most tas!s in Linux are performed using the shell commands,this module covers various shell commands and utilities that are re&uired while wor!ing on Linux

    The course also covers implementation of !ey programming concepts covered in %rogramming Logicand Techni&ues

    Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    5/43

    ENTR*#RO+ILE

    0 student who registers for the Linux module should "e a"le to perform the following tas!s

    3or! in a 3indows-"ased environment - The student will need to connect to Linux through theTelnet utility 4nowledge of the 3indows interface is re&uired to start Telnet

    Interact in 5nglish in a classroom environment - The classes will "e conducted in 5nglish Thecourseware will also "e in 5nglish The sessions will "e interactive in nature

    NIIT Linux 6

  • 7/27/2019 02 Sm1 Linux Cg

    6/43

    E,IT#RO+ILE

    0t the end of this module, the students will "e a"le to

    3or! in the Linux environment and carry out routine tas!s

    )ills Auired

    Identifying the features of the Linux operating system

    Identifying login and logout procedures

    7sing a text editor to create and maintain documents

    8anaging files on a Linux computer

    #reating and executing shell scripts

    0utomating tas!s using shell scripts

    #reating glo"al and local varia"les

    #hanging the shell prompt

    0pplying a password to secure a file or folder

    )ecuring files and directories "y changing file access permissions

    5xecute a process in the "ac!ground

    #alculate timing statistics re&uired to execute a process

    9 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    7/43

    +A/

    :1 3hat is ;ed

  • 7/27/2019 02 Sm1 Linux Cg

    8/43

    Torvalds, a student at the 7niversity of

  • 7/27/2019 02 Sm1 Linux Cg

    9/43

    NOTE+OR+AC0LT*

    Aou should have solved all the pro"lems in the )tudent @uide "efore the start of the module

    ;emem"er that the student is new to Linux and is wor!ing first time on the command line interface The

    student may face pro"lems with the syntax of the commands It is crucial that you encourage students to

    try out all the commands given in the student guide on the Linux operating system The student must tryout the examples and code given in the "oo! on the computer

    Aou must aim for the following

    The student is comforta"le with the command line interface of Linux

    The student appreciates the features of the Linux operating system

    The student is comforta"le with the vieditor as it is extensively used in the **%s module

    The student is encouraged to use the manand infopages

    It is faster to complete tas!s using the command line interface The advantage of executing commandsin the command line interface should "e explained to the students

    NIIT Linux B

  • 7/27/2019 02 Sm1 Linux Cg

    10/43

    OWTOIN)TALLTE)CRI#T)

    The sem1.tar.gzfile present on the T;8-#> under theshellscriptsfolder contains the scripts

    re&uired for the Linux module

    7se the following steps to install the scripts

    1( Log in to the Linux system as rootuser

    2( Insert the T;8-#> into the #>-;*8 drive and mount the T;8-#> using the following command

    mount /mnt/cdrom

    .( #reate a directory/root/sem1

    mkdir /root/sem1

    ( #hange your current directory to the +root+sem1

    cd /root/sem1

    6( #opy the sem1targ/ file present on the T;8-#> into the/root/sem1directory

    cp /mnt/cdrom/shellscripts/sem1.tar.gz /root/sem1

    9( ;estore the files from the "ac!up using the following command

    tar -zxvf sem1.tar.gz

    Aou are through with the installation of scripts

    0ppropriate directories would get created Aou would have to change to the appropriate directory to

    execute the scripts The EConfiguring the ResourceE section in the #@ explains the script to execute fordifferent lessons

    Note

    In case you do not have a #>-;*8 drive "ut have a floppy drive, copy the sem1.tar.gzfile from the

    T;8-#> into a floppy on a 3indows machine Then insert the floppy into the floppy drive of the Linuxserver To use the floppy, you would have to mount the floppy drive

    To mount the floppy drive that supports long file names, use the following command

    mount -t vfat /dev/fd0 /mnt/floppy.

    Aou can also use FT% to transfer the file to the Linux server 7se "inary mode to transfer the file

    0fter you have installed the scripts, you should get the following directories created common mrwee!2and mrwee!. These directories contain scripts and data files that are needed for demonstration and

    practice

    1G Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    11/43

    Aou need to change to the common directory where you will find seven very important scripts

    1( createmrusers 5xecute this script to create machine room users user1, user2, user.H user.G This

    script needs to "e run when the Linux server is installed

    2( createocruser 5xecute this script to create online classroom users ocruser1, ocruser2, H ocruser16

    and a login for faculty This script needs to "e run when the Linux server is installed

    .( delpassmr 5xecute this script if you want to clear passwords created "y some students on the userlogins

    ( delpassocr 5xecute this script if you want to clear the passwords on the the ocruser accounts

    6( clearmr 5xecute this script to delete all the files in the +home+user1, +home+user2, H +home+user.G

    directories These are the home directories of the machine room users This would also delete any

    su"directories the users may create

    9( clearocr 5xecute this script to delete all the files in the +home+user1, +home+user2, H +home+user.G

    directories These are the home directories of the ocr users

    3hen the students are going to wor! on the Linux server in the 8achine room, they should log in as

    user1, user2 user.G

    3hen the students are going to wor! on the Linux server in the *#;, they should login as ocruser1,

    ocruser2,H ocruser16

    #onfiguring the ;esource for the 8;

    Module Week number Script to be executed Location of the scripts, when the scripts areinstalled in the /root/sem1 directory

    MR 1 mrweek1 /root/sem1/mrweek1

    MR 2 mrweek2 /root/sem1/mrweek2

    MR 3 None No script needs to be executed

    NIIT Linux 11

  • 7/27/2019 02 Sm1 Linux Cg

    12/43

    )O0RCE)O+IN+ORMATION

    1 @o through the

  • 7/27/2019 02 Sm1 Linux Cg

    13/43

    LE))ON-)#ECI+ICIN#0T)

    Lesson One

    Ex2erienes

    5xplain the function of an operating system riefly explain the difference "etween multi user and

    single user operating system >iscuss the feature and architecture of Linux operating system 8entionvarious shells availa"le in Linux The students should understand the function of operating system

    It is the first time the students are going to wor! on the Linux platform 5xplain the login and the logoutprocedures of the Linux operating system The pro"lem statements relate to the scenario present in the

    starting of the "oo! >iscuss the scenario with the students >iscuss a"out the history of Linux >iscussa"out the philosophy of @N7 "y ;ichard )tallman Aou can access it at

    http++wwwgnuorg+gnu+thegnuproecthtml

    #over the commands cp, mv, rm, ls, and mkdirwith lots of examples as these are very important and

    also re&uired in the **%s module

    Con3i!urin! the Resoure

    The following points must "e noted for conducting the first class

    If you donJt li!e 3indows Telnet, you can download any good free Telnet software from theInternet *ne good Telnet utility is the Tera Term software availa"le at the following 7;L,http://hp.vector.co.jp/authors/VA00241/teraterm.html

    Aou can also download a very good utility called putty, which is a free telnet software fromhttp++wwwchiar!greenendorgu!+Ksgtatham+putty+ This utility gives a full screen view and does

    not have pro"lems of refreshing the screen faced sometime in 3indows telnet utility

    5xecute the script mrwee!1"efore starting with the unguided practice session

    Exa42les and Analo!ies

    *perating system can "e thougt of as a "an! manager in a "an! 3hen you go to the "an!, the "an!

    manager organi/es the wor!ing of the "an! so that you are a"le to complete your transactions smoothly

    For managing files and directories, you can give the example of managing physical files in cup"oards

    5xplain the concept of a computer filesystem and the need for a good filesystem Aou can explain thatin the a"sence of the file organi/ation capa"ility of an *), all the files would "e saved in the same

    directory and it would "e difficult to locate the file one needs 5xplain the features of the Linuxfilesystem, the inverted tree structure, and its advantages Aou can also state that even the 8) >*)

    filesystem is an adaptation of the 7nix filesystem Aou can relate to the 3indows 5xplorer output ifthey are familiar with the windows terms of folders and files

    NIIT Linux 1.

    http://www.gnu.org/gnu/thegnuproject.htmlhttp://www.gnu.org/gnu/thegnuproject.html
  • 7/27/2019 02 Sm1 Linux Cg

    14/43

    Additional In2uts

    3hen you are teaching students a"out the concepts of a multi user environment, you can tell them howmultiple users can log on to the server Tell them that 3indows NT is actually not a multi user system,

    as multiple users cannot wor! on the system simultaneously 3indows NT Terminal )erver edition is

    actually a multi user system

    Linux supports the following types of special files

    #haracter device files

    loc! device files

  • 7/27/2019 02 Sm1 Linux Cg

    15/43

    of the current userJs home directory In case you want to create multiple directories, you can specifythem in the same m!dir command For example,

    $mkdir dira dirb

    would create two directories

    In case you want to create a su"-directory, and its parent directory does not exist, you can specify the -p

    option with the mkdircommand so that the entire directory tree gets created

    For example,

    $mkdir -p grandfather/father/son

    This command would create the grandfather, father, and son directories if they do not exist

    Additional Exerises 3or the OCR51 0fter the year-end process, all the reports for the previous year have to "e moved to the directory

    named K+)ld*eports 3hich command would you use= '

  • 7/27/2019 02 Sm1 Linux Cg

    16/43

    )olutions5 0n!uided #ratie

    1 7se user1, user2Hetc to log in to the Linux server

    2 7se the *hocommand to list the users who have logged in to the Linux )erver

    . The answers are as follows

    a+ cd /etc

    b+ p*d

    c+ ls /etc

    d+ls /etc/".conf

    e+ man cp

    f+ cd ~

    g+ mkdir -p ./sales/trends ./sales/bills ./products./info/remote ./info/local

    h+ cp /home/customer/" ~

    i+ more /var/log/dmesg

    ,+ less ~/custdetails

    k+ $ cp ".sh ./info/remote/

    $ ls ./info/remote/

    l+ mv ".dat ~/sales/trends

    m+ rm ~/info/remote

    n+ rm ~/sales/trends

    19 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    17/43

    Lesson T"o

    Ex2erienes

    The need for pipes and filters should "e discussed when you solve any of the pro"lem statements

    >iscuss the options availa"le of the various filters 5xplain changing F0%s "oth with sym"ols andnum"ers 3hen the first demonstration in this lesson, 2>1 implemented using the find / -name

    dmesg -e'ec cat the contents of the result would scroll up 0fter explaining the pipes and

    redirection concept you can again execute the command as find / -name dmesg -e'ec cat

    23 err, to redirect error messages to an error file Aou can also enter4 find / -name

    dmesg -e'ec cat 5 lessto view the contents of the file page wise

    In the "eginning, students will not "e very comforta"le using the vieditor 3hile giving the demo for

    the vieditor, you must patiently explain the difference "etween the command mode and the insert

    mode of the vieditor

    Tell the students that operating systems have an editor software, which allows you to edit and save text

    files For example,

    3indows B6+BC+NT ? Notepad

    8)->*) ? 5dit

    7nix ? vi

    These editors usually do not have text formatting capa"ilities "ecause they are mostly used for editingthe system configuration files and creating scripts They are also more compact and faster than "ul!y

    word processors '8icrosoft 3*;>, )tar*ffice )tar3riter( If a student wants to enter the world ofLinux-"ased software development or Linux system administration, fluency with such an editor is

    imperative

    It is a good idea to teach students several extra commands in the vieditor, as they are expected to wor!

    on it throughout while programming in #$$ Aou must ensure that students enoy wor!ing on viand

    understand the rationale and advantages 'speed and flexi"ility( of using the vieditor

    Con3i!urin! the Resoure

    The following points must "e noted for conducting the first class

    To configure the machine room, run the script/root/sem1/mrwee!2/mrwee!2

    Exa42les and Analo!ies

    Aou can explain filters "y giving the example of the tea strainer that filters out li&uid tea and removes

    tea granules Filters are used many times in common day-to-day use )imilarly, filters in Linux are usedto extract the re&uired data The output of a filter need not "e the same as its input

    The data-flow in a pipe is always unidirectional Aou can ta!e the example of an oil refinery in whichcrude oil is the input to the first process 'the machine( The output of a process flows as input to the

    NIIT Linux 1D

  • 7/27/2019 02 Sm1 Linux Cg

    18/43

    next until the oil is completely refined Note that the flow is only in one direction The same is true forthe pipes in Linux Linux pipes also receive data from one end and send it to another, o"livious of the

    origin and the destination of the data

    Aou can relate to the vieditor with the note"oo! that we all carry 3e write our notes on the "oo!

    using a pen In this case, we can use the vieditor to write our notes to a computer file

    +A/

    :1 3hy are pipes and filters always discussed together=

    01 0lthough pipes and filters are two different utilities, they are usually discussed in the same contextThis is "ecause, they are mostly used together Filters ta!e input from the standard input It is a

    common practice to pass the output of a pipe to a filter

    :2 3hat is the default permission when a file is created=

    02 The umaskvalue determines the initial file permissions on a newly created file The value of

    umaskis turned off from the mode value, which is 999 for files and DDD for directories andexecuta"le files The mode value indicates that all the users have read and write permissions for afile y default, the umaskvalue is given as GG2 for a normal user and G22 for the root user, which

    means that every file that an ordinary user creates has the permission, 999 ? GG2 P 99 'rw-rw-r--(0s you notice, the user and the group have the write permission y default, the primary group of

    the user is the group owner of all the files that the user creates The umaskvalue of G22 will

    prevent users from modifying other usersJ private files The umaskvalue is set in the/etc/pro$ile

    file

    :.

  • 7/27/2019 02 Sm1 Linux Cg

    19/43

    0C 5macs was written "y ;ichard )tallman 'who is the founder of the Free )oftware Foundation andthe @N7 proect( and he still maintains it 5macs is one of the most popular and powerful text

    editors used on Linux 'and 7nix( It is !nown for its huge feature set, a"ility to "e easilycustomi/ed, and lac! of "ugs Its large feature set and a"ility to "e customi/ed are actually the

    result of how it was designed and implemented 5macs isnEt ust an editor It is written mostly in theprogramming language, Lisp 0t the core of 5macs is a full-featured Lisp interpreter written in #

    )o, in a sense, 5macs has an entire programming language "uilt in which you can use to customi/e,extend, and change its "ehavior 5macs is used as a text editor, a mail client, a N53)-reader, an

    integrated development environment, and is highly customi/a"le ;efer to the 3e" site,http://www.gnu.org/so$tware/emacs/emacs.html+, for further information on 5macs

    :B Is there a 3indows version for the vimeditor=

    0B Aes, there is a 3indows version of the vimeditor Further information can "e o"tained from the

    3e" site, www.vim.org.

    :1G 3hat is the difference "etween the lessand the morefilter=

    01G The morefilter is not capa"le of scrolling upwards whereas the lessfilter can scroll in "oth

    directions, up and down The lessfilter is also faster than the morefilter The morefilter still

    exists "ecause of legacy reasons as the previous version of 7nix had only the moreutility and not

    less

    :11 3hy is the filter lessfaster than the filter more=

    011 This is "ecause the filter lessaccepts data and caches the data )ince the lessfilter caches the

    data in the memory, moving up and down a page is possi"le and is faster

    Additional Exerises 3or the OCR5

    1 The file emp$eedb!.txtneeds to "e assigned the write permission for group users and others 3hichcommand will you use=

    01 chmod go6* empfeedbk.t't *;

    chmod 722 empfeedbk.t't

    2 3hat are the methods for securing your personal files and folders=

    02 %assword, F0%, loc!ing the wor!station, and password protection

    . The numeric e&uivalent of the read permission is 4

    3hat permissions are availa"le if a file has "een assigned D66 as F0%=

    0 0ll permissions for file owner, read and write permission for group users and other users

    6 Find the location of the file exports on your Linux server

    06 /etc/e'ports

    9 List all the users connected to your Linux server

    09cat /etc/pass*d 5 cut -d848 -f1

    D %redict the output of the following command

    ls l 5 tr s 8 8 5 cut d 8 8 f9:;

    NIIT Linux 1B

  • 7/27/2019 02 Sm1 Linux Cg

    20/43

    0D The command will display the si/e and the names of all the files in the current directory

    C The command to display the num"er of users currently logged in to the Linux computer iswho | wc l

    B The trfilter is used to replace a character with another character

    1G 3hat are the differences "etween the moreand lessfilters=

    01G The morefilter supports forward scaling only, whereas, the lessfilter supports forward and

    "ac!ward scaling

    11 %redict the output of the following command

    cat )8

    011 The contents of the file

  • 7/27/2019 02 Sm1 Linux Cg

    21/43

    will not do the needful

    $ cat file

  • 7/27/2019 02 Sm1 Linux Cg

    22/43

    The following options are availa"le with the cho*ncommand

    Option Function

    -' $t changes the ownership for files and directories recursi%el& under a particulardirector&'

    -f $t suppresses most of the error messages' (or instance) if the file name that &ouspecif& does not exist) chownwith the foption will not displa& an& error message'

    -v $t stands for %erbose' *his displa&s a status for all the files processed'

    -c $t is similar to %erbose) but this displa&s the status of the file processed onl& whenthe ownership is changed'

    --dereference $t affects the referent of each s&mbolic link) rather than the s&mbolic link itself'

    -h +ith the hoption) chownacts on s&mbolic links themsel%es instead of what the&

    point to'

    --reference(

  • 7/27/2019 02 Sm1 Linux Cg

    23/43

    vi $2G myfilec

    Aou can also use other editors in Linux li!e emacs, oe, or pico

    E4as editor

    The emacseditor is invo!ed "y the following command from the shell prompt

    emacs [command line switches] [file/s]

    Exa42le

    (%teveHlocalhost %teve)$ emacs

    The a"ove command will start the emacseditor and create a new file The following opening screen is

    displayed

    Opening Screen of the emacsEditor

    The following are some of the commonly used commands in the emacseditor

    Command Action

    ) Mo%es to pre%ious character

    f Mo%es to next character

    p Mo%es up one line

    n Mo%es down one line

    NIIT Linux 2.

  • 7/27/2019 02 Sm1 Linux Cg

    24/43

    v Mo%es to the next screen

    v Mo%es to the pre%ious screen

    a Mo%es to the beginning of the line

    e Mo%es to the end of the line

    h ,nters the emacsonline -elp

    s .earches forward for a string

    x u ndoes the last edit

    x c ,xits emacs

    x s .a%es the file

    g 0ancels the current command

    *his is used when &ou start to issue a command and then decide not to execute it'

    (or example) &ou issue the xcommand and then emacswaits for &ou to issue the

    action to be taken' Now if &ou wish to cancel the command) use the goption to come

    back to the main section of the document'

    Commands in emacs

    ;efer to the ta"le given "elow for some commands to delete text

    Command Action

    d eletes char

    k eletes line

    Deletion Commands

    ;efer to the ta"le given "elow for commands to copy lines

    Command Action

    * Marks text

    w 0uts the selected text

    + astes the text

    Commands to Copy Lines

    2 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    25/43

    )olutions5 Guided #ratie

    %ust a Minute6

    The details of various customers who have registered with >ia/ Telecommunication are stored in the"ustomerfile The sample data of the file is as follows

    80000018:8=ngela8:8%mith8:81B22E !adiance ourt8:8Iansas ity8:8Iansas880000028:8Jarbara8:8Kohnson8:8227 Jeach =ve.8:8=le'andria8:8Lirginia8800000E8:8Jetty8:8Milliams8:81

  • 7/27/2019 02 Sm1 Linux Cg

    26/43

    )olution

    $ grep 8Neorgia8 ustomer 5 cut -d8:8 -f2:E

    0lternatively, you can use redirection to accomplish this tas!

    $ grep 8Neorgia8 ustomer 3 tempfile

    $ cut -d8:8 -f2:E tempfile

    %ust a Minute6

    Aou need to export the contents of the file "ustomeretails.datpresent in the +/"ustomer"allsdirectory into a data"ase The exported data has to "e in uppercase 3rite a command to view the data

    in the new format on the screen, one screen-full at a time

    )olution

    $ cat ~/customeralls/customeretails.dat5tr 8(a-z)8 8(=->)8 5 less

    0n!uided #ratie

    Con3i!urin! the Resoure

    All the students must connect to the primar% Linux server for the Unguided Practice. You must

    execute the script /root/sem1/mrweek2/mrweek2to configure the student logins. You should !e

    logged in as the rootuser to execute the script.

    )olutions 0n!uided #ratie

    1 To search for the passwd file execute the command find / -name pass*d To redirect error

    messages to the file err execute the command find / -name pass*d 23 err

    2 find / -name ollege after you have located the #ollege file, you can use the cp

    command to copy it to your current directory The file would "e located under +home+customer

    directory 0lternatively you can use the following command

    find / -name ollege -e'ec cp . 23 /dev/null

    E. grep alifornia ollege

    A. *c -l ollege

    9. cat ollege 5 tr S(a-z)T S(=->)T

    B. cat northcolleges southcolleges 33 allcollege

    7. cut -d848 -f2:B ollege 5 tee olldata

    C a+ grep 8%teve8 messages

    "( grep -c 8%teve8 messages or grep 8%teve8 messages 5 *c -l

    29 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    27/43

    ;. chmod 000 messages

    vi messages

    Aou should get a message permission denied

    10. chmod A00 messages

    vi messages Aou would now "e a"le to view the contents "ut not "e a"le to modify it It wouldgive message read only file when you use the command w& to exit In case you still want to save

    it, you can use w&R command to save your changes

    11. mkdir impdata

    chmod 000 impdata

    cd impdata

    Aou should get permission denied message

    12. chmod u6r* impdata.

    Now you should "e a"le to change your current directory to this directory "ut you will not "e a"le

    to create a su"directory

    1. The students should use the vieditor to edit the file that is stored in the userEs home directory

    vi pro,plan

    a( setnu

    "( 8ove the cursor to the line num"er 1. and press dd

    c( 8ove the cursor to the line num"er D and press

    d( Type 4PUto &uit without saving

    e+ vi pro,plan

    f( 8ove the cursor to the first line and press oto insert a "lan! lin! after the current line

    g( Type V%followed "y 49to move to the third line

    h( 7se the yycommand to copy the line num"er E, then move the cursor to the end of file and

    press p

    i( 7se the ucommand to undo the paste option

    ( %ress 5)# followed "y /#liver It would search for *liver Now use the ; option to

    replace it with )teve %ress/again to repeat the last search 0gain press !to replace it with

    )teve

    !( 8ove the cursor to the fourth line and then move it right till it reaches SThe most S %ress the

    '!ey repeatedly to delete the line

    l( 8ove the cursor to line 6 and use the ; option to replace n with a( ;epeat the same step for

    line 9 to 1 and replace 2 with "(, . with c( and so on Aou can also delete the character n andinsert the series a( "( etc

    NIIT Linux 2D

  • 7/27/2019 02 Sm1 Linux Cg

    28/43

    m( %ress ddon the fifth line and then press pto place the line "elow the sixth line

    n( 7se the insert mode to add the text in the vieditor

    o( 7se the 4*Poption to save the file

    Additional Exerises5

    :1( The following command would give the re&uired outputls -l 5 grep 8W-..'8 5 tr -s 8 8 5 cut -d8 8 -f;

    X2+ 5xecute the command4 umask 022 Now when you create a file, its permission would "e BBB-022 Y BAAY -r*-r--rZ

    XE+ [se the 4r option to read the contents of the second file to thefirst file.

    Lesson Three

    Ex2erienes

    ;elate the concepts in this class with the concepts covered in %LT This is the first time the students

    would "e writing shell scripts 5xplain the concept of how to execute the shell script so that they area"le to create and execute the shell scripts ;elate the concepts covered in the shell script with the

    concepts covered in %LT 5xplain the logic of shell script using flowcharts

    The while, until and for commands are similar in nature 5xplain the similarity "etween these

    commands

    Con3i!urin! the Resoure

    The following points must "e noted for conducting the class

    There is no script for 3ee! 6 8;

    Exa42les and Analo!ies

    )hell scripts are used to automate tas!s Aou can show the students some examples of system shellscripts that are used for many tas!s, the intricacies of which are hidden from users For example, the

    shell script/usr/sbin/sambais used to start and stop the )am"a services

    Aou can also tell the students that a set of shell scripts is availa"le with the faculty, which copies the

    re&uired files into the home directories of all the users 0t this point, you could open one of the scriptsand show its contents to the students

    2C Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    29/43

    Aou can also tell students a"out the file bashpro$ile, which is a special shell script that is executedautomatically when a user logs in This file is used for configuring the environment information for a

    Linux user Aou may want to open a sample.bashpro$ilefile to display its contents to students

    +A/

    :1 3hat is the e&uivalent of a shell script in 3indows+8) >*)=

    01 In 8) >*), the "atch files are similar to the shell scripts of Linux The e&uivalent of the shell

    script, .pro$ile, is the autoexec.batfile 3indows also has "atch files with a .batextension0dditionally, 3indows NT files with the extension cmdare used The .cmdfiles are more powerful

    than the .batfiles

    :2 #an Linux act as a programming language=

    02 The statement Linux - 0 programming languageU is incorrect Linux is an operating system and

    not a programming language such as #$$ 0lthough Linux provides a lot of programmingconstructs, they are typically used to configure the environment and automate tas!s and not for

    writing applications

    Note 3riting shell scripts is commonly referred to as scripting

    :. #an one shell script execute another=

    0. Aes, in fact it is very common to call one shell script from another Aou can see the contents of the

    file .bashpro$ile, which first executes the file .bashrcfrom the home directory of the user

    : 3hat are the application areas of shell scripts=

    0 )hell scripts are used for various reasons, "oth "y the end user and the system administrator Theend user typically writes shell scripts to automate common activities, such as copying files The

    system administrator uses shell scripts for various administrative tas!s, such as ta!ing a "ac!upVarious shell scripts come with the Linux system and can "e used in areas, such as starting and

    stopping services, and setting the user environment

    Additional In2uts

    Aou can ma!e the students refer to system shell scripts, such as

    /usr/sbin/samba

    /etc/rc.d/init.d/

    /etc/pro$ile

    /etc/inittab

    Additional Exerises

    1 0 shell script can "e executed "y the WWWW command '0ns shor bash(

    2 The WWWWW environment varia"le stores the path to the userJs home directory '0ns \#@V(

    NIIT Linux 2B

  • 7/27/2019 02 Sm1 Linux Cg

    30/43

    . 3rite a shell script that accepts two num"ers num1 and num2 It should interchange their values

    and display on screen

    echo -n 8Vnter the first number4 8

    read num1echo -n 8Vnter the second number4 8read num2tempY$num1num1Y$num2num2Y$tempecho 8Lalue of first number Y $num18echo 8Lalue of second number Y $num28

    )olutions5 Guided #ratie

    %ust a Minute...

    3rite a shell script that calculates the num"er of unanswered &ueries at the call center The script shouldaccept the total num"er of &ueries reported in a day and the num"er of &ueries answered to calculate the

    num"er of unanswered &ueries

    Total num"er of unanswered &ueries P Total num"er of &ueries - Num"er of answered &ueries

    )olution#reate a file called callpendingusing the vieditor with the following contents

    echo 8&lease enter the total number of Pueries reported today.8read totalPueriesecho 8&lease enter the number of Pueries ans*ered.8read ans*eredpendingY$??totalPueries-ans*ered++echo 8Gumber of calls pending Y $pending8

    Type the following command to execute the shell script

    $ bash callpending

    0lternatively, you can assign the execute permission to the file and use the following command toexecute the shell script

    $ chmod 6' callpending

    $ ./callpending

    %ust a Minute...

    .G Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    31/43

    0t the call centers, the performance of a #ustomer #are 5xecutive is measured "y the percentage of&ueries answered for the day 3rite a shell script that displays the grade given to an employee on the

    "asis of the percentage of calls answered for the day

    Percentage of calls answered the same day Grade

    #4 5%erage

    ! 4 and #64 7ood

    !64 8utstanding

    )olution

    Create a file called gradeusing the vieditor with the following contents:

    ]U/bin/bashecho 8Vnter the percentage of calls ans*ered same day.8read actual

    if ( $actual -le F0 )then echo 8^our Nrade is =verage.8elif ( $actual -gt F0 -a $actual -le ;0 )then echo 8^our Nrade is Nood.8else echo 8^our Nrade is #utstanding.8

    fi

    Type the following command to execute the shell script

    $ bash grade

    0lternatively, you can assign the execute permission to the file and use the following command toexecute the shell script

    $chmod 6' grade

    $ ./grade

    %ust a Minute...

    >ia/ Telecommunications offers its customers various services Aou need to create a menu that displays

    the service names, and when the customer selects a name, its description is displayed

    The following ta"le displays the various services and their description

    NIIT Linux .1

  • 7/27/2019 02 Sm1 Linux Cg

    32/43

    SerialNumber

    Service Name Description

    1 7lobal Roam 9ou :ust need one cell;phone number where%er &ou tra%el across the world'

    2 s calling'

    ? ial a i@@a 9ou can order for a pi@@a from &our cell;phone'

    )olution

    3rite the following shell script

    2/)in/)ash

    echo 0ist of 3ervices ffered )+ 5iaz 6elecommunications echo 1$ 7lo)al 'oamecho &$ 8-mailecho %$ 9ail on 9oveecho 4$ aller-:5echo ;$ 5ial a izzaecho n 3elect the service for which +ou need more information =1-;> ? read choicecase ,choice in1$ echo @ou Aust need one cell-phone num)er wherever +ou travel acrossthe world. ""&$ echo @ou can record +our messages when +ou are not a)le to take acall.""

    %$ echo @ou can receive e-mail messages on +our cell-phone.""4$ echo @ou can displa+ the callers telephone num)er on +our handsetscreen whenever +ou receive a call so that +ou know whoBs calling."";$ echo @ou can order for pizza from +our cell-phone.""C$ echo @ou have selected an invalid option.""esac

    Aou can assign the execute permission to the file and use the following command to execute the shell

    script

    $ chmod 6' menu$ ./menu

    %ust a Minute...

    Aou need to store the names, e-mail addresses, and telephone num"ers of eight employees wor!ing at

    the #ustomer #are #enter The data is to "e stored in the file ccemplo(eein the following format

    5mployee#ode 5mployeeName 5-mail Telephone-Num"er

    The sample data to "e entered is as follows

    1GGG )arah sarah"X&mailcom 'D.2(2.-D9.1GG1 %eter peterXspeedmailcom '2.(.2-2.6

    1GG2 >avid davidcXspeedmailcom '62(6.-2.6

    1GG. %aul paulXdia/com '62.(2.-2.61GG Linda lindalXdia/telcom '6(6.-6D9

    .2 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    33/43

    1GG6 oseph osephmXspeedmailcom 'C6.(.2-2.61GG9 Nancy nancyXdia/telcom '.2(.9.-.96

    1GGD ;uth ruthpXdia/telcom '9.(D6-.961GGC ane anesXspeedmailcom 'D9(.9-6D

    The employee code for these employees should "e automatically generated and should range from 1GGG

    to 1GGC The shell script should as! you for the details "ased on the employee code

    )olution

    To accept the details of the employees and store them in the file, type in the following shell script and

    store it in a file called acceptdata.sh

    ]U/bin/bashecodeY1000*hile ( $ecode -le 100F )do echo 8Vnter data for the employee *ith Vmployee ode Y $ecode8 echo -n 8Vmployee Game 4 8

    read name echo -n 8Vmail =ddress 4 8 read email echo -n 8

  • 7/27/2019 02 Sm1 Linux Cg

    34/43

    1.echo 8\#@V Y$\#@V8echo 8&=

  • 7/27/2019 02 Sm1 Linux Cg

    35/43

    8.max(Dfor##count(1 " count

  • 7/27/2019 02 Sm1 Linux Cg

    36/43

    c( 7se thepscommand to find the process id of the in$initewhoprocess 7se the kill -Ocommand

    to !ill the process kill -O &14O;

    d(

    for??++

    doecho 8o you *ant to kno* *ho is online_ 8read ans*erif ( $ans*er Y 8n8 -o $ans*er Y 8G8 )then breakfi*hodone

    7.

    time find / -name dmesg &! /dev/null

    Additional Exerises5

    Ans *+

    #ontents of the mainfile are

    echo 8@ain @enu8echo 81+ Oile commands8echo 82+ irectory commands8

    echo 8E+ Qist the users currently logged in8read choicecase $choice in1+ ./filecommand2+ ./directorycommandE+ *hoesac

    #ontents of the file$ilecommand

    echo 8Mhich file command *ould you like help on_8echo 81+ cp8echo 82+ mv8

    echo 8E+ rm8echo 8please enter your choice8read choicecase $choice in1+ man cp2+ man mvE+ man rmesac

    #ontents of the director(commandfile

    echo 8Mhich directory command *ould you like help on_8echo 81+ mkdir8

    echo 82+ rmdir8echo 8E+ls 8

    .9 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    37/43

    echo 8&lease enter your choice8read choicecase $choice in1+ man mkdir2+ man rmdirE+ man ls

    esac

    Fns &$

    aY0bY1countY2echo $aecho $b*hile ( $count -le ; )do??cY$a6$b++echo $c

    aY$bbY$c??countY$count61++done

    Fns %$

    if = , -lt 1 >then echo @ou have not specified the filename. Hsage? Kuick)ackup

    then if = -d P/)ackup > then cp ,1 P/)ackup else mkdir P/)ackup cp ,1 P/)ackup fielse echo 6he file +ou have specified does not existfi

    NIIT Linux .D

  • 7/27/2019 02 Sm1 Linux Cg

    38/43

    )OL0TIONTOA==ITIONALE,ERCI)E)INA##EN=I,

    Ans"er 1echo 8Vnter a file or directory name 48read fnameif test -f $fnamethen echo 8$fname is an ordinary file - display_8read ansif test $ans Y `y`then if test -r $fname then cat $fname

    else echo 8%orry: $fname has no read permission8 fifielif test -d $fnamethen echo 8$fname is a directory file - display_8read ansif test $ans Y `y`then if test -r $fname then ls -l $fname else echo 8%orry: $fname has no read permission8 fifi

    else echo 8$fname is neither an ordinary file nor a directory8

    Ans"er 8echo 8Vnter the string8read strecho 8

  • 7/27/2019 02 Sm1 Linux Cg

    39/43

    revstrY$revstr$tempchar lenYe'pr $len - 1doneecho $revstr

    Ans"er ;echo 8Vnter string8read strlenYecho $str 5 *c -clenYe'pr $len - 1lYe'pr $len / 2ctrY1flagY0*hile test $ctr -le $ldo aYecho $str 5 cut -c$ctr bYecho $str 5 cut -c$len if test $a UY $b

    then flagY1 break fi ctrYe'pr $ctr 6 1 lenYe'pr $len - 1doneif test $flag -eP 0 then echo 8%tring is palindrome8 else echo 8%tring not a palindrome8fi

    Ans"er s Not nix home page' 0ontains lots of interesting articles b&

    Richard .tallman'

    6A www'rpm'orgB Cots of rpms to download and install on the Cinux s&stem'

    14A www'linuxworld'comB $nformation on Cinux'

    11A httpB//www'linux'comB $nteresting articles on Cinux'

    12A httpB//www'linux;india'orgB -ome page of *he Cinux $ndia 8rgani@ation'

    13A httpB//freshmeat'netB Cots of source code and programs to download'

    1=A httpB//&olinux'comB ocumentation on Cinux'

    1?A www'isc'tamu'edu/Jlewing/linux/B *he location from where &ou see the *ux' *he logo of Cinux'

    1GA httpB//www'woodsoup'org/pro:s/tuxDaKfh/doc/B *he complete histor& of *ux'

    1HA httpB//www'gimp'org/B -ome page of using 7$M L*he 7N $mage Manipulation rogramA'*his tool was used to draw *ux'

    NIIT Linux 1

  • 7/27/2019 02 Sm1 Linux Cg

    42/43

    A==ITIONAL'OO)

    ill all, Teach Aourself Linux in 2 avid %itts and ill all,*ed &at 3inux nleashed

    Na"a ar!a!ati,3inux 'ecrets, I>@ oo!s 3orldwide

    0eleen Frisch,5ssential '(stem Administration6 2nd 5dition

    8i!e Lou!ides, '(stem ,er$ormance 7uning

    %atric! 4illelea, 8eb ,er$ormance 7uning: 'peeding p the 8eb

    Cycle # Activity/Problem No. Duration (InMins)

    Cycle1

    C!"

    Cesson 1B 8b:ecti%es ?

    7etting .tarted 24

    *he Cinux 8. 1?

    irector& 0ommands in Cinux 34

    (ile 0ommands in Cinux 34

    .ummar& 14

    otal 11$

    Cycle"

    C!"Cesson 2B 8b:ecti%es ?

    .tandard (iles ?

    Redirection

    (ilters 1?

    5M ?

    ipes

    5M H

    5M 14

    Cocating a (ile in Cinux 14

    5ssigning ermissions to (iles 14

    ,ditors ?

    *he %i ,ditor ?.ummar& 14

    2 Linux NIIT

  • 7/27/2019 02 Sm1 Linux Cg

    43/43

    otal 1$%

    Cycle&

    C!"

    Cesson 3B 8b:ecti%es ?

    7etting .tarted ?