Study of Unix Os

Embed Size (px)

Citation preview

  • 8/2/2019 Study of Unix Os

    1/28

    Study of UNIX OS

    EX. NO. :

    DATE :

    AIM: To study the UNIX OS.What is UNIX?

    UNIX is an operating system which was first developed in the 1960s, and has been under

    constant development ever since. By operating system, we mean the suite of programswhich make the computer work. It is a stable, multi-user, multi-tasking system for servers,desktops and laptops.UNIX systems also have a graphical user interface (GUI) similar to Microsoft Windowswhich provides an easy to use environment. However, knowledge of UNIX is required foroperations which arent covered by a graphical program, or for when there is no windowsinterface available, for example, in a telnet session.Types of UNIX

    There are many different versions of UNIX, although they share common similarities. Themost popular varieties of UNIX are Sun Solaris, GNU/Linux, and MacOS X.The UNIX operating system

    The UNIX operating system is made up of three parts; the kernel, the shell and the

    programs.The kernelThe kernel of UNIX is the hub of the operating system: it allocates time and memory toprograms and handles the filestore and communications in response to system calls.As an illustration of the way that the shell and the kernel work together, suppose a usertypes rm myfile (which has the effect of removing the file myfile). The shell searches thefilestore for the file containing the program rm, and then requests the kernel, throughsystem calls, to execute the program rmon myfile. When the process rm myfile has finishedrunning, the shell then returns the UNIX prompt % to the user, indicating that it is waitingfor further commands.The shell

    The shell acts as an interface between the user and the kernel. When a user logs in, thelogin program checks the username and password, and then starts another program calledthe shell. The shell is a command line interpreter (CLI). It interprets the commands the usertypes in and arranges for them to be carried out. The commands are themselves programs:when they terminate, the shell gives the user another prompt (% on our systems).The adept user can customise his/her own shell, and users can use different shells on thesame machine. Staff and students in the school have the tcsh shell by default.The tcsh shell has certain features to help the user inputting commands.Filename Completion By typing part of the name of a command, filename or directoryand pressing the [Tab] key, the tcsh shell will complete the rest of the name automatically.If the shell finds more than one name beginning with those letters you have typed, it will

    beep, prompting you to type a few more letters before pressing the tab key again.History The shell keeps a list of the commands you have typed in. If you need to repeat acommand, use the cursor keys to scroll up and down the list or type history for a list ofprevious commands.Files and processes

    Everything in UNIX is either a file or a process.A process is an executing program identified by a unique PID (process identifier).

  • 8/2/2019 Study of Unix Os

    2/28

    A file is a collection of data. They are created by users using text editors, runningcompilers etc.Examples of files:a document (report, essay etc.)the text of a program written in some high-level programming language

    instructions comprehensible directly to the machine and incomprehensible to a casual user,for example, a collection of binary digits (an executable or binary file);a directory, containing information about its contents, which may be a mixture of otherdirectories (subdirectories) and ordinary files.The Directory Structure

    All the files are grouped together in the directory structure. The file-system is arranged in ahierarchical structure, like an inverted tree. The top of the hierarchy is traditionally calledroot (written as a slash / )

    Most UNIX file system types have a similar general structure, although the exact detailsvary quite a bit. The central concepts aresuperblock, inode, data block, directory block, and indirectionblock. The superblock contains information about the file system as a whole, such as its size(the exact information here depends on the file system). An inode contains all informationabout a file, except its name. The name is stored in the directory, together with the numberof the inode. A directory entry consists of a filename and the number of the inode whichrepresents the file. The inode contains the numbers of several data blocks, which are usedto store the data in the file. There is space only for a few data block numbers in the inode,however, and if more are needed, more space for pointers to the data blocks is allocateddynamically. These dynamically allocated blocks are indirect blocks; the name indicatesthat in order to find the data block, one has to find its number in the indirect block first.Like UNIX, Linux chooses to have a single hierarchical directory structure. Everythingstarts from the root directory, represented by /, and then expands into sub-directoriesinstead of having so-called drives. In the Windows environment, one may put ones files

    almost anywhere: on C drive, D drive, E drive etc. Such a file system is called ahierarchical structure and is managed by the programs themselves (program directories),not by the operating system. On the other hand, Linux sorts directories descending from theroot directory / according to their importance to the boot process.Linux, like Unix also chooses to be case sensitive. What this means is that the case,whether in capitals or not, of the characters becomes very important. This feature accountsfor a fairly large proportion of problems for new users especially during file transferoperations whether it may be via removable disk media such as floppy disk or over the wireby way of FTP.

  • 8/2/2019 Study of Unix Os

    3/28

    The following bin/ dev/ home/ lost+found/ proc/ sbin/ usr/ boot/ etc/ lib/ mnt/ root/ tmp/var/ are explained in detail./sbin This directory contains all the binaries that are essential to the working of thesystem. These include system administration as well as maintenance and hardwareconfiguration programs./bin In contrast to /sbin, the bin directory contains several useful commands that are usedby both the system administrator as well as non-privileged users./boot This directory contains the system.map file as well as the Linux kernel. Lilo placesthe boot sector backups in this directory./dev This is a very interesting directory that highlights one important characteristic of theLinux filesystem everything is a file or a directory. Look through this directory and you

    should see hda1, hda2 etc, which represent the various partitions on the first master drive ofthe system. /dev/cdrom and /dev/fd0 represent your CDROM drive and your floppy drive./etc This directory contains all the configuration files for your system. Your lilo.conf filelies in this directory as does hosts, resolv.conf and fstab./home These are the user home directories, which can be found under /home/username./lib This contains all the shared libraries that are required by system programs. Windowsequivalent to a shared library would be a DLL file./lost+found Linux should always go through a proper shutdown. Sometimes your systemmight crash or a power failure might take the machine down. Either way, at the next boot, alengthy filesystem check using fsck will be done. Fsck will go through the system and tryto recover any corrupt files that it finds. The result of this recovery operation will be placed

    in this directory./mnt This directory usually contains mount points or sub-directories where you mountyour floppy and your CD./opt This directory contains all the software and add-on packages that are not part of thedefault installation./proc This is a special directory on your system./root We talked about user home directories earlier and well this one is the homedirectory of the user root.

  • 8/2/2019 Study of Unix Os

    4/28

    /tmp This directory contains mostly files that are required temporarily./usr This is one of the most important directories in the system as it contains all the userbinaries. /usr/src/linux contains the source code for the Linux kernel./var This directory contains spooling data like mail and also the output from the printerdaemon. The above content briefs about Linux and the file system of Linux.BASIC COMMANDS IN UNIX

    EX. NO. :DATE

    :AIM: To study the basic commands in UNIX.COMMANDS:

    1. TASK : To display the system date and time.COMMAND : date.SYNTAX : date.EXPLANATION: This command displays the current system date and time on thescreen.OUTPUT :

    2. TASK : To display the current month.COMMAND : date.SYNTAX : date +%m.EXPLANATION: This command displays the current month on the screen.OUTPUT :

    3. TASK : To display the name of the current month.COMMAND : date.SYNTAX : date +%h.EXPLANATION: This command displays the name of the current month on the

    screen.OUTPUT :

    4. TASK : To display the current system date.COMMAND : date.SYNTAX : date +%d.EXPLANATION: This command displays the current system date on the screen.OUTPUT :

    5. TASK : To display the current system date (year).COMMAND : date.SYNTAX : date +%y.EXPLANATION: This command displays the current year on the screen.OUTPUT :

    6. TASK : To display the current system time.COMMAND : date.SYNTAX : date +%H.EXPLANATION: This command displays the current system time (in hours) on thescreen.OUTPUT :

    7. TASK : To display the current system time.COMMAND : date.SYNTAX : date +%M.EXPLANATION: This command displays the current system time (in minutes) on the screen.

  • 8/2/2019 Study of Unix Os

    5/28

    OUTPUT :

    8. TASK : To display the current system time.COMMAND : date.SYNTAX : date +%S.EXPLANATION: This command displays the current system time (in seconds) on the screen.OUTPUT :

    9. TASK : To display the calendar of the current month.COMMAND : calendar.SYNTAX : cal.EXPLANATION: This command displays the calendar of the current month on thescreen.OUTPUT :

    10. TASK : To display user-defined message.COMMAND : echo.SYNTAX : echo message.EXPLANATION: This command displays on the screen the argument of the echocommand.

    OUTPUT :

    11. TASK : To display the details of all users.COMMAND : who.SYNTAX : who.EXPLANATION : This command lists the information about all the users who have

    logged on to that system.OUTPUT :

    12. TASK : To display the user detail.COMMAND : who.SYNTAX : whoami.EXPLANATION : This command displays information about the current user of the

    system on the screen.OUTPUT :

    13. TASK : To create a directory.COMMAND : make directory.SYNTAX : mkdir.EXPLANATION : This command is used to create a new directory with the specified

    name.EXAMPLE :

    OUTPUT :

    14. TASK : To change directory.COMMAND : change directory.SYNTAX :

    cd directory name.EXPLANATION : This command is used to switch from one directory to another.EXAMPLE :

    OUTPUT :

    15. TASK : To delete a directory.

  • 8/2/2019 Study of Unix Os

    6/28

    COMMAND : remove directory.SYNTAX :

    rmdir directory nameEXPLANATION : This command is used to delete the specified directory.EXAMPLE :

    OUTPUT :

    16. TASK : To come out of a sub-directory.COMMAND : change directory.SYNTAX : cd ..

    EXPLANATION : This command helps in switching to the main directory.OUTPUT :

    17. TASK : To list all the files and directories.COMMAND : list.SYNTAX :

    ls.EXPLANATION : This command displays all the files and directories of the system.OUTPUT :

    18. TASK : To create a file.

    COMMAND : cat.SYNTAX :

    cat> file name.EXPLANATION : This command leads to the creation of a new file with the specifiedfile name and contents.EXAMPLE :

    OUTPUT :

    19. TASK : To view a file.COMMAND : cat.SYNTAX :

    cat file name.EXPLANATION : This command displays the contents of the specified file.EXAMPLE :

    OUTPUT :

    20. TASK : To copy a file.COMMAND : copy.SYNTAX :

    cp sourcefile destinationfile.EXPLANATION : This command produces a copy of the source file and is stored in

    the specified destination file by overwriting its previouscontents.EXAMPLE :

    OUTPUT :

    21. TASK : To move a file.COMMAND : move.SYNTAX :

    mv sourcefile destinationfile.EXPLANATION : After moving the contents of the source file into destination file,the source file is deleted.EXAMPLE :

    OUTPUT :

    22. TASK : To display / cut a column from a file.

  • 8/2/2019 Study of Unix Os

    7/28

    COMMAND : cut.SYNTAX :

    cut c no. filename.EXPLANATION : This command displays the characters of a particular column in thespecified file.EXAMPLE :

    OUTPUT :

    .23. TASK : To delete a file.COMMAND : remove.SYNTAX :

    rm file name.EXPLANATION : This command deletes the specified file from the directory.EXAMPLE :

    OUTPUT :

    24. TASK : To retrieve a part of a file.COMMAND : head.SYNTAX :

    head -no. of rows file name.EXPLANATION : This command displays the specified no. of rows form the topof the specified file.EXAMPLE :

    OUTPUT :

    25. TASK : To retrieve a file.COMMAND : tail.SYNTAX : tail -no. of rows file name.EXPLANATION : This command displays the specified no. of rows form the bottomof the specified file.EXAMPLE :

    OUTPUT :

    26. TASK : To sort the contents of a file.COMMAND : sort.SYNTAX :

    sort file name.EXPLANATION : This command helps in sorting the contents of a file in ascendingorder.EXAMPLE :

    OUTPUT :

    .27. TASK : To display the no. of characters in a file.COMMAND : word count.SYNTAX :

    wc file name.EXPLANATION : This command displays on the screen the no. of rows, words, and

    the sum of no. of characters and words.EXAMPLE :

    OUTPUT :

    28. TASK : To display the calendar of a year.COMMAND : cal.

  • 8/2/2019 Study of Unix Os

    8/28

    SYNTAX :

    cal year.EXPLANATION : This command displays on the screen the calendar of the specified

    year.EXAMPLE :

    OUTPUT :

    Listing Directory Contents1. Log in to the system.2. Issue the command pwd . What is the path?________________________________________________________________________3. Issue the command ls. What do you observe?________________________________________________________________________4. Issue the command ls l . In an abbreviated form, what do you observe?________________________________________________________________________________________________________________________________________________5. Issue the command ls a. In an abbreviated form, what do you observe?________________________________________________________________________

    ________________________________________________________________________6. Issue the command cd /var.7. Issue the command pwd . What is the path?________________________________________________________________________8. Issue the command ls. What do you observe?________________________________________________________________________9. Issue the command ls l . In an abbreviated form, what do you observe?________________________________________________________________________10. Issue the command ls a. In an abbreviated form, what do you observe?________________________________________________________________________11. Issue the command ls i . Record the inode value for each file and directory. inodefilename inode filename________________________________________________________________________________________________________________________________________________Root

    In your own words, explain the meaning of:1. The Root________________________________________________________________________2. Administrator Root________________________________________________________________________3. Home directory Root________________________________________________________________________4. Group Root

    ________________________________________________________________________5. What is the difference between the user root and group root.________________________________________________________________________Beside the UNIX commands below, define what each command does.

    cd

    pwd

  • 8/2/2019 Study of Unix Os

    9/28

    ls

    cp

    echo

    rm

    mkdir

    rmdir

    Frequently used UNIX commands

    Command Result

    ls lists files in current working directory

    ls *.out lists all files in current directory that end in .out

    ls -l lists files giving details including file size

    pwddisplays full-path name of your current workingdirectory on screen (stands for present workingdirectory)

    cd dirname changes directory to dirname

    cd ..

    changes directory to one above the current

    directory

    cdwith no argument, takes you to your homedirectory

    mkdir dirname creates new directory dirname

    rmdir dirname removes empty directory dirname

    cp filename newname makes a copy offilename with the name newname

    cp ../filename .copies filename in directory one tier above to currentdirectory giving it the same name

    mv filename newname renames filename to newname (mv stands for move)

    cat filename displays contents offilename on screen

    more filenamedisplays filename contents one screen at a time(Enter key scrolls through file by line; space barscrolls through by screen)

    head filename displays first 10 lines offilename on screen

  • 8/2/2019 Study of Unix Os

    10/28

    tail filename displays last 10 lines offilename on screen

    rm filenamedeletes filenamewithout double check (rm stands for remove)

    grep string filenamedisplays lines from filename containing stringon

    screen./ filename & runs job filename in the background

    qsub filenamesends job filename to queue (where qsub is asubmission script file in your bin directory)

    qstat lists jobs running on queue

    qstat -a lists only your jobs

    qdel job# deletes job with numberjob# from queue

    ps lists processes you have running

    ps -ef lists all processes

    kill pid# kills process with ID numberpid#

    kill -9 pid#kills (with the sure kill signal) process with IDnumberpid#

    kill -kill 0kills all processes you have running and logs youoff

    man commandname displays manual page for command commandname

    man -k keyword lists manual pages for commands related tokeyword

    lp filename prints filename on printer in room 4241

    chmod ### filename

    changes read, write, execute mode offilenameExample: to set the privileges forfilename so thatthe owner has the ability to read, overwrite andexecute the file, the group has the ability to readand execute the file, and everyone else has noaccess to the file, use the command chmod 750

    filename.

    owner group all

    rwx rwx rwx

    4 2 1 4 2 1 4 2 1

    sum numbers for each

    of the three

    categories of user

    Ctrl+c kills current operation

    Ctrl+hdelete (always works even when delete keydoesnt)

    Ctrl+d logout

    UNIX: vi Editor

  • 8/2/2019 Study of Unix Os

    11/28

    EX. NO. :

    DATE :AIM: To study the basic of vi Editor.UNIX: vi EditorGeneral IntroductionThe vi editor (short for visual editor) is a screen editor which is available on almost allUnix systems. Once you have learned vi, you will find that it is a fast and powerful editor.vi has no menus but instead uses combinations of keystrokes in order to accomplishcommands.There are three basic modes of vi:Command mode

    This is the default when you enter vi. In command mode, most letters, or short sequencesof letters, that you type will be interpreted as commands, without explicitly pressing Enter. If you press Esc when youre in command mode, your terminal will beep at you. This is avery good way to tell when youre in command mode.Insert mode

    In insert mode, whatever you type is inserted in the file at the cursor position. Type a

    (lowercase letter a, forappend) to enter insert mode from command mode; press Esc to endinsert mode, and return to command mode.Line mode

    Use line mode to enter line oriented commands. To enter line mode from command mode,type a colon ( : ). Your cursor moves to the bottom of the screen, by a colon prompt. Type aline mode command, then press Enter. Any sensible command from the Unix line editor exwill work, and a few are good to know about. These commands are indicated in thishandout by a colon in front of the command. Each time you use a line mode command, youmust type a colon to enter line mode, then type the command by the colon prompt at thebottom of the screen, then press Enter when you finish typing the command. (The searchcommands starting with / and ? work similarly.

    General Command Information

    As mentioned previously, vi uses letters as commands. It is important to note that ingeneral vi commands:are case sensitive lowercase and uppercase command letters do different thingsare not displayed on the screen when you type themgenerally do not require a Return after you type the command.You will see some commands which start with a colon (:). These commands are excommands which are used by the ex editor. ex is the true editor which lies underneath vi in other words, vi is the interface for the ex editor.The vi editor has three modes: 1) command mode, 2) last-line mode, and 3) input mode.Note: The vi editor does not understand the mouse and only understands commands

    typed from the keyboard.The UNIX text editor, vi, is used by the UNIX administrator (superuser) to create or editfiles. Usually these files require configuration information to host certain UNIX servers orI/O functions. Users can start a vi session by typing vi followed by the file name to becreated or edited. In our example, we will create a file named linux. The vi editor willcreate a new file if the file does not already exist. If a file, in our example linux, doesexist in our current directory, the vi editor will open linux for editing. Once we type vi

  • 8/2/2019 Study of Unix Os

    12/28

    linux and hit the enter key, we are placed in command mode where communications isdirected to the vi editor. Type the following command to initiate our vi session:

    vi linux

    You will be presented with a full, empty screen. Each line will begin with the tilde (~)symbol. The tilde is vis way of indicating that a line is empty in its edit register. The vieditor uses the first 24 of 25 lines viewable on the terminal screen as insert lines.The last line (line number 25) is used for entering commands to the shell and is referred toas the last-line mode. In this space, our filename appears with the message linux and[new file].When you open a file, the cursor is placed at the top, left corner of the screen. You are saidto be in Command Mode. You can issue commands that act upon the text in the file. Inthe command mode, pressing a key does not show on the screen, but performs a functionlike moving the cursor to the next line or deleting a line. The command mode cannot be

    used to enter text. The keyboardspace barmoves the cursor ahead one space at a time. Thekeyboard backspace key moves the cursor backwards one space at a time.To enter text, you must be in Insert Mode. There are ten (10) keys that place you in InsertMode. Each key has an upper case and a lower case function. The quickest way to learninsert mode is to simply type a lower case i for insert. The following chart the shows 10ways to enter Insert Mode:

    Command Function

    i Inserts text to left of the cursor. Existing text shifted right

    I Inserts text at beginning of line. Existing text shifted right

    a Appends text to right of the cursor. Existing text shifted right

    A Inserts text at end of the lineo Opens a line below the current line the cursor is on

    O Opens line above the current line the cursor is on

    rch Replaces a single character (ch) under cursor. No [Esc] required

    R Replaces text from cursor to right. Existing text overwritten

    s Replaces character under cursor with any number of characters

    S Replaces entire line that cursor is on

    Important!To exit input mode, you must enter the [Esc] key.

    The Last-line Mode is opened by pressing and holding the [shift] key and the [:] colon keysimultaneously ([shift] + [colon]). If this fails to place you in Last-line mode, hit theescape key to move from insert mode to command mode. Upon entering this dualkey-stroke combination, the cursor moves to the bottom, left corner of the screen andappears as a colon : . This mode allows the vi user to send commands to the actual UNIXshell. Commands used in the Last-line Mode write the contents of a file to the hard drive,reads contents into the existing file from another file, or quits the vi session. Once a

  • 8/2/2019 Study of Unix Os

    13/28

    command has been executed, the cursor moves back to the top, left of the screen. To moveback to the top of the screen without executing a command, press the key. While inlast-line mode (where we communicate with the shell and not with the vi editor), thefollowing commands can be executed:

    Last-line commands used to communicate with the UNIX/Linux shell:Command Function

    :w Writes file to hard drive and remains in editing mode

    Writes file and quits editing mode

    :wq Writes file and quits editing mode

    :q Quits editing mode with no changes made to file

    :q! Forces vi to quit and exits to the command-line shell

    :w >> note1 Appends current file contents to new file, note1

    :r Reads contents of into current vi file

    :n1, n2w customer.sql Writes selected lines, n1 through n2, to customer.sql

    :.w customer.sql Writes current line [.] to file, customer.sql:$w customer.sql Writes last line [$] to file, customer.sql

    :! Used to execute a shell command without leaving vi

    [Crtl-z] Suspends current session and escaped to UNIX shell

    Lets begin our next lab exercise by opening an empty file named linux and manuallyinserting a script entitled, The Linux Story.

    Note: The vi editor does not perform an automatic word-wrap, so hit the key at the end of a normal line (80

    characters). This will help with editing features, perform a carriage feed, and begin a new line.

    While you are entering The Linux Story, periodically write the file to the hard drive bytyping and then entering the last-line command + . A colon appears atthe bottom, left of the screen. Enter w and press . If a file fails to write, use+ plus the ! symbol, such as :w! . The bang sign ( ! ) forces a write to the harddrive.The linux Story

    Linus Torvalds, creator of the Linux Operating System, was born Dec 28, 1969 in Helsinki,Finland. His grandfather had a Commodore VIC-20 that he had the opportunity to workwith; by age ten he was already dabbling in programming. He enrolled at the University ofHelsinki in 1989, and in 1990 he took his first C programming class.

    ( after entering the above information, write and quit vi by :wq! )

    Note: Since vi places its text in a buffer, it is wise to frequently write a file to disk at specificintervals. This will prevent data loss if the system fails or an incorrect key combinationcloses our file. Saving the buffer is performed in the last-line mode. Every command in thismode is preceded by a : (colon) and followed by the key. To save, enter last-linemode and then enter w (for write) and press the enter key.

  • 8/2/2019 Study of Unix Os

    14/28

    Opening a new line: place the cursor on the main title, The Linux Story, and open a newline underneath the title by typing a lower case o. You can now enter, By Anonymous.Since the o placed you in the Insert Mode, you must enter [Esc] to return to the CommandMode.

    Replacing text: replacing text can be done by one character at a time or a string ofcharacters at a time. Use the r, R, s, and S keys. Place the cursor over the l in linux in thefirst line. Now hit the r key and then type an upper case L. This changes the word linux toLinux.

    Note: vi momentarily switches from the Command Mode to the Insert Mode when r is pressed and back to the CommandMode as soon as the character is entered.

    Replacing a word: replacing a word can be done using the cw (change word) command.Place the cursor on the letter D where Linus birthday is shown as Dec. Now, type cw.Dec should disappear. Now type December. This changes the word Dec to December.Press the Escape key.

    Replacing a single character with multi-character text: use the s key after placing the cursorat the beginning of the word string to be replaced.Replacing an entire line with another line: use the S key after placing the cursor at thebeginning, or at any point, of the sentence to be replaced.Determining your current cursor position by line number: use the [Ctrl-g] key to see whatline number your cursor is on. The line number is displayed in the last-line position at thebottom right of the screen.Placing the cursor on a predetermined line: Use the G key followed by a line number toplace the cursor on a particular line (While in Command Mode enter, 12G to go to the 12 th

    line).Moving the cursor from the beginning of or to the end of the current line: enter a caret (^)

    to move to the beginning of the current line or enter a dollar ($) to move to the end of thecurrent line.Moving around in a document: Use the up-down, right-left keyboard keys or use b, e, andw to move between words in a sentence.Deleting a character: use x to delete a character.Deleting an entire line: use dd to delete the entire current line.Undoing a mistake: Use the u to undo a key sequence mistake.Searching for a pattern string of characters: use the / (forward slash) followed by thepattern being searched for. To find the first occurrence of the word Linux, type /Linux andpress . Using ? instead of/will search backwards.Searching and replacing a string pattern: enter the last-line mode and type:

    1,$s/pattern1/pattern2/ where 1 indicates the first line of the file and $ indicates the last lineof the file. Pattern1 is the string searched for and pattern2 is the string replacing pattern1.To practice this important editing function, enter the Last-Line Mode [:] and type1,$s/Story/Song/ and [Enter].Undo Song and change it back to Story by hitting [esc] and then u.Exit out of vi by entering the last-line mode and typing wq!Name the three modes used with the vi text editor.List the 10 ways to be placed in the Insert Mode using vi.

  • 8/2/2019 Study of Unix Os

    15/28

    Show the key-stoke sequence used to enter the Last-Line Mode using vi.In vi, which letter can be used to undo an editing mistake?In vi, what does the dd command do?Editing Files

    1. Log on to the system.

    2. At the moment we need to create a new directory and then change to it. Issue thecommand:mkdir /lab

    Then change to the /lab directory.

    3. Note your location.

    Prompt: ____________________________________________________________

    Full working Path: ____________________________________________________

    4. Issue the command touch testfile.

    5. Issue the command ls l testfile. Record the results of the display.

    Filename: ___________________________________________________________

    File Attributes: ________________________________________________________

    File Owner: ___________________________________________________________

    File Group: ___________________________________________________________

    File Size: _____________________________________________________________

    File Creation Date: _____________________________________________________

    6. Issue the command vi testfile2. You have now opened the vi editor to a new file calledtestfile2. You are in the command mode. Enter the command the letter i . You are now inthe insert mode, able to type in text.

    7. Enter the following text:

    Name: {your name}

    IP Address: {your system IP address}

    File: testfile2 using vi

    I am a great student and am working hard to prove myself as

    an A student!

    8. Strike the ESC key. This places you into the command mode. If you hear additionalbeeps from the (small) computer speaker, you are already in the command mode.

  • 8/2/2019 Study of Unix Os

    16/28

    9. Enter the command :w . This saves the text to the hard drive.

    10. Enter the command :q . This exits the vi editor.

    11. Enter the command vi testfile3.

    12. Enter the following text:

    Name: {your name}

    IP Address: {your system IP address}

    File: testfile3 using pico

    My classmates are great people too.

    13. List the contents of the directory. Record the results.

    1. Log onto the system.

    2. What is the path? ______________________________________________

    3. Change to the /lab directory ( create the lab directory)

    4. Record the full path of the directory. (if it is not /lab, you made an error)

    ________________________________________________________________________

    5. Using the vi text editor, create a new file called test1.

    6. Insert into the test1 file the following:

    Test file 1.

    My name is {your name}.

    I am learning Linux.

    7. Save the file (look at the bottom of the screen to WriteOut the file). Then exit.

    8. Using the vi text editor, create a new file called test2.

    9. Insert into the test2 file the following:

    Test file 2.

    Created by {your name}.

    This is a simple file.

    10. Save the file and exit.

    11. Issue the command cat test1 . Record what you observe.

  • 8/2/2019 Study of Unix Os

    17/28

    ________________________________________________________________________

    12. Issue the command cat test2 . Record what you observe.

    __________________________________________________________

    13. Issue the command cat test1 test2 . Record what you observe.

    ________________________________________________________________________14. Issue the command more test1 . Record what you observe.

    ________________________________________________________________________

    15. Issue the command history | more . Scroll down through the file. Try to scroll up. (Notethat only the space bar will scroll through the file. The | , or pipe, will be dicussed later.)Record what you observe.

    ________________________________________________________________________

    16. Issue the command less test2 . Record what you observe.

    ________________________________________________________________________

    17. Issue the command history | less . Scroll up and down through the file using both the Up /Down Arrow keys and the Page Up / Down keys.

    18. Issue the command history | head . Record what you observe.

    ________________________________________________________________________

    19. Issue the command history | tail . Record what you observe.

    ________________________________________________________________________

    20. Issue the command history | tac . Record what you observe.

    ________________________________________________________________________

    21. Issue the command cat > test3 and hit ENTER.

    22. Enter the following lines:

    Test file 3.

    Created by {your name}.

    Created using the cat command.

    {on this line, enter a CTRL-D}

  • 8/2/2019 Study of Unix Os

    18/28

    23. Display the file with the cat command, record your observations.

    ________________________________________________________________________

    Case Study

    1. Test to see if the two files (test1 and test2) may be displayed by different displayutilities.Discuss your findings.2. Compare the differences between the output of the following:cat E testfile3cat n testfile3hexdump c testfile3od ta testfile3od tc testfile3xxd testfile3Record your observations:Moving One Character at a Time

    Try using your direction keys to move up, down, left and right in your file. Sometimes, youmay find that the direction keys dont work. If that is the case, to move the cursor onecharacter at the time, you may use the h,j, k, and l keys. These keys move you in thefollowing directions:h left one space l right one space

    j down one space k up one space

    If you move the cursor as far as you can in any direction, you may see a screen flash orhear a beep.Moving among Words and Lines

    While these four keys (or your direction keys) can move you just about anywhere you wantto go in your file, there are some shortcut keys that you can use to move a little morequickly through a document. To move more quickly among words, you might use thefollowing:w moves the cursor forward one word

    b moves the cursor backward one word (if in the middle of a

    word, b will move you to the beginning of the current word).

    e moves to the end of a word.

    To build on this further, you can precede these commands with a number for greatermovement. For example, 5w would move you forward five words; 12b would move you

    backwards twelve words. [You can also use numbers with the commands mentionedearlier. For example, 5j would move you down 5 characters.]ShortcutsTwo short cuts for moving quickly on a line include the $ and the 0 (zero) keys. The $ keywill move you to the end of a line, while the 0 will move you quickly to the beginning of aline.Screen MovementTo move the cursor to a line within your current screen use the following keys:

  • 8/2/2019 Study of Unix Os

    19/28

    H moves the cursor to the top line of the screen.

    M moves the cursor to the middle line of the screen.

    L moves the cursor to the last line of the screen.

    To scroll through the file and see other screens use:

    ctrl-f scrolls down one screen

    ctrl-b scrolls up one screen

    ctrl-u scrolls up a half a screen

    ctrl-d scrolls down a half a screen

    Two other useful commands for moving quickly from one end to the other of a documentare G to move to the end of the file and 1G to move to the beginning of the file. If youprecede G with a number, you can move to a specific line in the document (e.g. 15G wouldmove you to line 15).Moving by Searching

    One method for moving quickly to a particular spot in your file is to search for specifictext. When you are in command mode, type a / followed the text you wish to search for.When you press Return, the cursor will move to the first incidence of that string of text. Youcan repeat the search by typing n or search in a backwards direction by using N.Deleting (or Cutting) Characters, Words, and LinesTo delete a character, first place your cursor on that character. Then, you may use any ofthe following commands:x deletes the character under the cursor.

    X deletes the character to the left of your cursor.

    dw deletes from the character selected to the end of the word.

    dd deletes all the current line.

    D deletes from the current character to the end of the line.

    Preceding the command with a number will delete multiple characters. For example, 10xwill delete the character selected and the next 9 characters; 10X will delete the 10 charactersto the left of the currently selected character. The command 5dw will delete 5 words, while4dd deletes four lines.Pasting Text using PutOften, when you delete or cut text, you may wish to reinsert it in another location of thedocument. The Put command will paste in the last portion of text that was deleted since

    deleted text is stored in a buffer. To use this command, place the cursor where you wish thedeleted text to appear. Then use p to reinsert the text. If you are inserting a line orparagraph use the lower case p to insert on the line below the cursor or upper case P toplace in on the line above the cursor.Copying Text with YankIf you wish to make a duplicate copy of existing text, you may use the yank and putcommands to accomplish this function. Yank copies the selected text into a buffer and

  • 8/2/2019 Study of Unix Os

    20/28

    holds it until another yank or deletion occurs. Yank is usually used in combination with aword or line object such as the ones shown below:yw copies a word into a buffer (7yw copies 7 words)

    yy copies a line into a buffer (3yy will copy 3 lines)

    Once the desired text is yanked, place the cursor in the spot in which you wish to insert the

    text and then use the put command (p for line below orP for line above) to insert thecontents of the buffer.Replacing or Changing Characters, Words, and LinesWhen you are using the following commands to replace text, you will be put temporarilyinto insert mode so that you can change a character, word, line, or paragraph of text.r replaces the current character with the next character you enter/type.

    Once you enter the character you are returned to command mode.

    R puts you in overtype mode until you hit ESC which will then return

    you to command mode.

    cw changes and replaces the current word with text that you type. A dollar

    sign marks the end of the text you're changing. Pressing ESC when youfinish will return you to command mode.

    Inserting a Blank LineTo insert a blank line below the line your cursor is currently located on, use the o key andthen hit ESC to return to the command mode . Use O to insert a line above the line thecursor is located on.Appending TextYou can use the append command to add text at any place in your file. Append (a) worksvery much like Insert (i) except that it insert text afterthe cursor rather than before it.Append is probably used most often for adding text to the end of a line. Simply place yourcursor where you wish to append text and press a. Once youve finished appending, pressESC

    to go back to command mode.Joining LinesSince vi does not use automatic word wrap, it is not unusual in editing lines to end up withlines that are too short and that might be improved if joined together. To do this, place yourcursor on the first line to be joined and type J. As with other commands, you can precede Jwith a number to join multiple lines (4J joins 4 lines).UndoingBe sure to remember this command. When you make a mistake you can undo it. DO NOTmove the cursor from the line where you made the change. Then try using one of thefollowing two commands:u undoes the last change you made anywhere in the file. Using u again

    will "undo the undo".

    U undoes all recent changes to the current line. You can not have moved

    from the line to recover the original line.

    Closing and Saving FilesWhen you edit a file in vi, you are actually editing a copy of the file rather than theoriginal. The following sections describe methods you might use when closing a file,quitting vi, or both.Quitting and Saving a File

  • 8/2/2019 Study of Unix Os

    21/28

    The command ZZ (notice that it is in uppercase) will allow you to quit vi and save the editsmade to a file. You will then return to a Unix prompt. Note that you can also use thefollowing commands::w to save your file but not quit vi (this is good to do periodically in

    case of machine crash!).

    :q to quit if you haven't made any edits.

    :wq to quit and save edits (basically the same as ZZ).

    Quitting without Saving EditsSometimes, when you create a mess (when you first start using vi this is easy to do!) youmay wish to erase all edits made to the file and either start over or quit. To do this, you canchoose from the following two commands::e! reads the original file back in so that you can start over.

    :q! wipes out all edits and allows you to exit from vi.

    EX. NO. :DATE

    :SHELL PROGRAMMINGA Linux shell is a command language interpreter, the primary purpose of which is totranslate the command lines typed at the terminal into system actions. The shell itself is aprogram, through which other programs are invokedWhat is a shell script ?A shell script is a file containing a list of commands to be executed by the Linux shell.shell script provides the ability to create your own customized Linux commandsLinux shell have sophisticated programming capabilities which makes shell script powerfulLinux toolsHow to work with shell?Step1:

    In the dollar prompt type$ vi < file name>Where vi is the editor ,it will open a new window in which you can type the program youwantStep2:

    After typing the program press ESC and : together then at the bottom of the vi screen youcan see i.e. prompt .In that type as wq which means write and quit i.e. the content what istyped will be written and saved into that file that has been createdStep3:

    Once wq is typed at the : prompt ,the prompt would change to $ symbol in which you haveto do the following$ sh < file name >

    Sh command is used to run the shell program is the name of the file for which the output is to be gotBasically to print a text in the your shell programs echo command is usedIdentifying System Variables

    The shell is the primary agency that determines a users environment. Determine whichshell that you are using by typing the following command:echo $SHELL

  • 8/2/2019 Study of Unix Os

    22/28

    Write the output2. PATH is one of the important system variables. It provides the shell with a searchablepath to explore in order to find commands stored in various directories in the file systemstructure. Once the command entered on the command line is found, the shell can interpretthe command. Determine your shells path settings.echo $PATH

    Write your output

    3. HOME stores the users home directory after a successful login. Each users homedirectory is named after their user account name. Determine your home directory settings.echo $HOME

    Write your output

    4. LOGNAME is the variable that holds your username.echo $LOGNAME

    Write your output

    5. MAIL provides UNIX with an absolute path to each users mailbox. Determine yourMAIL settings.echo $MAILWrite your output6. MAILCHECK determines how often the shell checks for the arrival of new mail.

    MAILCHECK is set for 600 seconds by default and can be modified by the super user.Determine your MAILCHECK settings.

    echo $MAILCHECK

    Write your output7. PS1 is the primary prompt string for the shell. Determine your PS1 settingsecho $PS1

    Write your output8. PS2 is the secondary string for the shell. If the shell does not have enough information

    on the command line to interpret the command, it presents the user with the secondaryprompt. The user can finish the command line on the secondary prompt line and then hitthe enter key. Determine your PS2 settingsecho $PS2

    Write your output

  • 8/2/2019 Study of Unix Os

    23/28

    9. CDPATH is the variable search path used by the cd command. CDPATH works thesame as PATH except it locates directories and not shell commands. Determine yourCDPATH setting.echo $CDPATHWrite your output

    TERM is the variable that indicates the type of terminal you are using. Determine yourTERM setting.echo $TERM

    Write your outputSYNTAX FOR LOOPING STATEMENTS

    IF THEN-ELSE CONSTRUCT

    if [ condition]then else

    statementsfi (end of if)WHILE

    while doDoneCASE

    Case $ in;;;;..

    .

    .

    .*) ;;esacFor loop

    For(( intitialization;condition;incremetation/decrementation))

    AREA OF THE TRIANGLEAim:

    To write a shell script to find the area of the triangleAlgorithm:

    Step1 : get the base and heightStep2 : calculate the areaStep3 : Display the result

  • 8/2/2019 Study of Unix Os

    24/28

    SQUARE OF THE NUMBERAim:

    To write a shell script which accepts a number less than 50 and display its squareAlgorithm:

    Step1 : Get the numberStep2 : Check if the number is less than 50. If the number is less than 50 then compute

    the square of the numberStep3 : Display the result.ODD NUMBER GENERATIONAim:

    To write a shell script display a list of odd numbers below a given numberAlgorithm:

    Step1 : Get the limitStep2 : Initialize count to 1Step3 : Display the list of odd numbers by incrementing count by 2 until the given limit.FIBONACCI SERIES

    Aim:

    To write a shell script to print the Fibonacci series

    Algorithm:Step1 : get the limitStep2 : add the first two numbers to produce the third numberStep3 : add the second and third number to get the fourth number and so onStep4 : display the seriesSTUDENT MARKS

    Aim:

    To write a shell script to read the marks of 5 subjects from user and calculate the averageand gradeAlgorithm:

    Step1 : Read the MarksStep2 : calculate the average

    Step3 : if the average is greater than 75 then assign grade as Distinctionif the average is between 60 to 75 then assign grade as First Classif the average is between 50 to 59 then assign grade as Second Classelse then assign grade as FailVOWEL OR NOTAim:

    To write a shell script to find whether a given character is vowel or constantAlgorithm:

    Step1 : Read the charactersStep2 : If it matches with any of the vowels a,e,i,o,u print it as vowelStep3 : Otherwise print it as a constant

    MENU DRIVEN PROGRAM

    Aim:

    To write a shell script for a menu driven program.Algorithm:

    Step1 : Get the option, use case statement to display the various functionsStep2 : first option to view the content of the home directory

  • 8/2/2019 Study of Unix Os

    25/28

    Second option to list the users who have loggedThird option to print the present working directoryFourth option to count the words, characters and lines of a fileFifth option to print the type of fileStep3 : Display the result according to the option chose

    PALINDROME CHECKINGAim:To write a shell script to check whether the given string is a palindrome or notAlgorithm:

    Step1 : read an input stringStep2 : find the length of the stringStep3 : extract the input string into another variable starting from the last characterStep4 : check whether the input string and the reversed string are the sameStep5 : if so, display given string is a palindrome else display given string is nota palindromeUSER LOGGED IN OR NOTAim:

    To write a shell script to accept the name of the user and check out if the user hasLogged in or not.Algorithm:

    Step1 : accept username from command lineStep2 : use grep filter ,extract username from /dev/null fileStep3 : check whether the input username is in the /dev/null file.If the username is present inthe file,display message as user has logged inelse, display the message as user has not logged inCOUNT THE ORDINARY FILE AND DIRECTORYAim:

    To write a shell script to find the number of ordinary files and directory files in the current

    directory .Algorithm:

    Step1 : Read the directory nameStep2 : Check if the number of command line arguments read .Step3 : If the number of arguments read is less than one, then display the message asinvalid messageStep4 : Check whether the file is ordinary file or directory file[-f or d]Step5 : Using grep filter, extract the number of files and directory files in two variablesStep6 : Display the count of files and directory filesDISPLAY THE FILE PERMISSIONAim:

    To write a shell script to accept the filenames and display the file permission from the longlisting of filesAlgorithm:

    Step1 : Accept filenames from command lineStep2 : In a for loop, using the cut command extract the file permission from the longlisting of filesStep3 : Display the filenames and their permission.UPPERCASE CONVERSION

    Aim:

  • 8/2/2019 Study of Unix Os

    26/28

    To write a shell script to convert the content of given files to uppercase lettersAlgorithm:

    Step1 : Accept filenames to be converted from command lineStep2 : Using the tr command to convert the content of file to upper caseStep3 : Display the content of converted filesFILE MANAGEMENTAim:

    To write a C program to perform file operations using file descriptorAlgorithm:

    Step 1: Get file name from userStep 2: Get the string and find the length of the stringStep 3: Open the file in write modeStep 4: Write the string in the fileStep 5: Close the fileStep 6: Open the file in read modeStep 7: Read the contents of the file and store it in a temporary storage spaceStep 8: Print the buffer contents on the screen

    Step 9: Close the file.PROCESS MANAGEMENT

    Aim:

    To write a C program to create a new process using forkAlgorithm:

    Step1 : Create the process using fork() system callStep2 : Check the process id of current processIf it is 0 then display as child process and also display the process id of current andparent processElse it is a parent process and display the process id of current process and parent processIMPLEMENTATION OF UNIX COMMANDS

    Aim:

    To write a C program to implement grep unix commandsAlgorithm:

    Step1 : Use system function to implement grep unix commands

    35eeeitmech[cse@localhost cse]$ cat dept|tr "[a-z]" "

  • 8/2/2019 Study of Unix Os

    27/28

    [A-Z]"CSEECEEEEITMECH13.[root@localhost root]# pg

    It displays the output of a command on the screenpage by page.

    14.[root@localhost root]# more

    To Displays the output page by page[ece@localhost ece]$ ls | more000000123003004500711010010001101

    36121221231234123456789012413213314315918--More

    Press Enter to see the next page.15.

    [

    root@localhost root]# cmp

    Compare any two files, including binary files. Ittakes two filenames as arguments.[ece@localhost ece]$ cat > collegediva vh2346 jan vh2345kavi vh2387naru vh2876subi vh2498[ece@localhost ece]$ cat > college1DHONI VH2876RAINA VH2398KAIF VH2657

    37HARI VH2765SRI VH4567[ece@localhost ece]$ cmp college college1college college1 differ: byte 1, line 1[

    ece@localhost ece]$ cat college[ece@localhost ece]$ cmp -b college college1college college1 differ: byte 1, line 1 is 144 d 104 D16.[root@localhost root]# diff

    Files are compared on line by line basis.[ece@localhost ece]$ cat collegediva vh2346 jan vh2345kavi vh2387naru vh2876subi vh2498[ece@localhost ece]$ cat college1dhoni vh2387raina vh2389subi vh2498sachin vh2564diva vh2346[ece@localhost ece]$ diff -e college college11,5cdhoni vh2387raina vh2389subi vh2498

    38sachin vh2564diva vh2346[ece@localhost ece]$ diff -b college college11,4c1,2< diva vh2346< jan vh2345< kavi vh2387< naru vh2876---> dhonivh2387> raina vh23895a4,5> sachin vh2564> diva vh234617.[root@localhost root]# comm

  • 8/2/2019 Study of Unix Os

    28/28

    Compare and displays lines common as well asunique to two files.[ece@localhost ece]$ comm -1 college college1dhoni vh2387raina vh2389subi vh2498sachin vh2564diva vh2346[ece@localhost ece]$ comm -13 college college1dhoni vh2387

    63SHELL PROGRAM:echo "Enter a Number"read ni=`expr $n - 1 t=0while [ $i -ge 2 ]dop=`expr $n % $i if [ $p -eq 0 ]thent=expr $t + 1 fii= expr $i - 1 doneif

    [ $t -gt 0 ]thenecho "The Number $n is not a Prime Number"

    64elseecho "The Number $n is a Prime Number"fiSAMPLE OUTPUT:[root@localhost Shell]# sh prime.shEnter a Number2The Number 2 is a Prime Number[root@localhost Shell]# sh

    prime.shEnter a Number4The Number 4 is not a Prime NumberRESULT:

    65Thus the Shell Program to check if the given number is prime or not, was executed andthe output was verified.SUMS OF DIGITS OF AN INTEGEREx. No.13AIM:To write a Shell Program to calculate the sum of digits of an Integer.

    ALGORITHM:Step 1:Start

    Step 2:Read the Integer as num Step 3:Initialize the value of sum=0.Step 4:While the value of num is greater than 0, solve the following expressions. Step 5:Find the remainder of num by 10 and store in y Step 6:Add sum with y and store it in sum Step 7:Divide num by 10 and store the value in num Step 7:Close the while loopStep 8:

    Print the ResultStep 9:StopSHELL PROGRAM:echo "Enter a