ULP Lab Practical.doc

Embed Size (px)

Citation preview

  • 7/29/2019 ULP Lab Practical.doc

    1/54

    Practical file

    Of

    UNIX & Linux

    programming

    SUBMITTED TO:SUBMITTED BY:

    Er. JitinKumar(Lect. In C.S.E. Deptt.) Roll No.-2908136K.I.T.M., Kurukshetra Branch-C.S.E.(A3)

  • 7/29/2019 ULP Lab Practical.doc

    2/54

    KURUKSHETRA INSTITUTE OF TECHNOLOGY & MANAGEMENTPehowa Road, Bhor SaidanKurukshetra

  • 7/29/2019 ULP Lab Practical.doc

    3/54

    INDEX

    S.NO.

    EXPERIMENT NAME DATE REMARK S

  • 7/29/2019 ULP Lab Practical.doc

    4/54

    Practical No.1

    AIM - Install Linux on a PC having some other previouslyinstalled operating system. All Operating Systems shouldbe usable.

  • 7/29/2019 ULP Lab Practical.doc

    5/54

    To install Red Hat Enterprise Linux 5 on your computer, take the followingsteps:

    Step 1:- Right Click on My Computer and go to manage option

    Step 2:- Click on Disk Management option and delete a partition to makeit free for RHEL installation.

    Step 3:- Insert the media that youll use to boot the Red Hat EnterpriseLinux 5 installation program. It can be the first Red Hat Enterprise Linux 5 CDor DVD.

    Step 4:- Restart the system.

  • 7/29/2019 ULP Lab Practical.doc

    6/54

    Step 5:- When you see the boot prompt press ENTER key to install ingraphical mode.

    Step 6:- Installation Method: - Choose your installation method (like LocalCDROM) and press OK

    Step 7:- Press Skip to skip the Media test and start the installation.

  • 7/29/2019 ULP Lab Practical.doc

    7/54

    Step 8:- Welcome Screen:- The Welcome screen does not prompt you forany input. From this screen you can access the Release Notes for Red Hat

    Enterprise Linux 5.0.0 by clicking on the Release Notes button. Click on theNext button to continue.

    Step 9:- Language Selection: - Using your mouse, select a language to

    use for the installation.Once you select the appropriate language, click Next to continue.

  • 7/29/2019 ULP Lab Practical.doc

    8/54

    Step 10:- Keyboard Configuration:- Using your mouse, select the correctlayout type (for example, U.S. English) for the keyboard you would prefer touse for the installation and as the system default (refer to the figurebelow).Once you have made your selection, click Next to continue.

    Step 11:- Enter the Installation Number: - Enter your InstallationNumber. This number will determine the package selection set that isavailable to the installer. If you choose to skip entering the installationnumber you will be presented with a basic selection of packages to installlater on.

  • 7/29/2019 ULP Lab Practical.doc

    9/54

    Step 12:- Create Custom Layout:-

    Click next once you have made your selections to proceed.

    Step 13:- Partitioning Your System: - If you chose to create a customlayout, you must tell the installation program where to install Red HatEnterprise Linux. This is done by defining mount points for one or more diskpartitions in which Red Hat Enterprise Linux is installed. You may also needto create and/or delete partitions at this time.

  • 7/29/2019 ULP Lab Practical.doc

    10/54

    Step 14:- Adding Partitions: - To add a new partition, select the new

    button. Add the desired partitions.

    Step 15:- Boot Loader Configuration: - To boot the system without bootmedia, you usually need to install a boot loader. A boot loader is the firstsoftware program that runs when a computer starts. It is responsible for

    loading and transferring control to the operating system kernel software. Thekernel, in turn, initializes the rest of the operating system. Once youveconfigured your partitions, set up a boot loader. If you select No Boot LoaderWill Be Installed, youll need to use a third-party boot loader such as PartitionMagic or Microsofts NTLDR. Unless you want to set up a Boot LoaderPassword or Configure Advanced Boot Loader Options, click Next.

  • 7/29/2019 ULP Lab Practical.doc

    11/54

    Step 16:- Network Configuration: - Configure your connection to thenetwork. If you dont want the DHCP server to assign a hostname (or youdont have a DHCP server), you can assign it manually, as shown here. ClickNext to move on.

    Step 17:- Time Zone Configuration: - Set your time zone by selecting thecity closest to your computer's physical location. Click on the map to zoom into a particular geographical region of the world.From here there are two ways for you to select your time zone: Using your mouse, click on the interactive map to select a specific city(represented by ayellow dot). A red X appears indicating your selection.

  • 7/29/2019 ULP Lab Practical.doc

    12/54

    You can also scroll through the list at the bottom of the screen to selectyour time zone. Usingyour mouse, click on a location to highlight your selection.

    Step 18:- Set Root Password: - Setting up a root account and password isone of the most important steps during your installation. The root account isused to install packages, upgrade RPMs, and perform most systemmaintenance. Logging in as root gives you complete control over yoursystem.

    Step 19:- Package Group Selection: - There are two packagecustomization screens available. Everyone sees the screen shown next. (Thechoices are slightly different for Red Hat Enterprise Linux 5 Client.) You canaccept the defaults, select available options, and/or select Customize Now.

  • 7/29/2019 ULP Lab Practical.doc

    13/54

    Its usually best to customize modestly (Ive selected the Customize Nowoption), based on the requirements on your particular Installation andConfiguration exam. Click Next. (If you dont select Customize Now, skip thenext step.)

    Step 20:- Package Group Details.

    Step 21:- Installing packages defined by the user.

  • 7/29/2019 ULP Lab Practical.doc

    14/54

    The next screen congratulates you for completing the installation. The nextstep is to reboot your computer into RHEL. Click Reboot.

  • 7/29/2019 ULP Lab Practical.doc

    15/54

    PRACTICAL NO. 2

    Aim: - Familiarize with Unix/Linux logging/logout andsimple commands.

    Login/Logout: -

    It identifies you as a particular user.It starts up your own shell and desktop.It gives you appropriate permissions.

    Syntax: - Login:Password:$ - User, # - RootLogout is use to logout from particular user session,

    who: - Show who is logged into the system. With no options, list the namesof users currently logged in, their terminal, the time they have been loggedin, and the name of the host from which they have logged in. An optionalsystem file (default is /etc/utmp) can be supplied to give additionalinformation.

    Syntax: - who [options] [file] who am iOption: - am i: - Print the username of the invoking user.-u, --users :- Print a list of the users who are logged in.

    ps: - Report on active processes. ps has three types of options. GNU longoptions start with two hyphens, which are required. BSD options may be

    grouped and do not start with a hyphen, while Unix98 options may begrouped and require an initial hyphen. The meaning of the short options canvary depending on whether or not there is a hyphen. In options, listarguments should either be comma-separated or space-separated andplaced inside double quotes. In comparing the amount of output produced,note that e prints more than a and l prints more than f for each entry.

    Syntax: - ps [options]Option: - - a: - As a, list all processes on a terminal.-d :- Select all processes except session leaders.-e, -A :- Select all processes.

    cat: - Read (concatenate) one or more files and print them on standard

    output. Read standard input if no files are specified or if - is specified as oneof the files; input ends with EOF. You can use the > operator to combineseveral files into a new file, or >> to append files to an existing file. Whenappending to an existing file, use Ctrl-D, the end-of-file symbol, to end thesession.

    Syntax: - cat [options] [files]Options: - -b, --number-nonblank: - Number all nonblank output lines,starting with 1.

  • 7/29/2019 ULP Lab Practical.doc

    16/54

    -E, --show-ends: - Print $ at the end of each line.-n, --number :- Number all output lines, starting with 1.-s, --squeeze-blank :- Squeeze down multiple blank lines to one blank line.

    wc: -To count the number of characters , words & lines in particular file.Syntax: - wc[options][file]

    Options: - -c: - To count characters only.-w :- To count only words.-l :- To count only lines.

    cal: - Print a 12-month calendar (beginning with January) for the given year,or a one-month calendar of the given month and year. month ranges from 1to 12. year ranges from 1 to 9999. With no arguments, print a calendar forthe current month.

    Syntax: - cal [options] [[month] year]Options :- -j :- Display Julian dates (days numbered 1 to 365).-m :- Display Monday as the first day of the week.-y :- Display entire year.

    date: - Print the current date and time. You may specify a display format.format can consist of literal text strings (blanks must be quoted) as well asfield descriptors, whose values will appear as described in the followingentries (the listing shows some logical groupings). A privileged user canchange the system's date and time.

    Syntax: -date [options] [+format] [date]Option: --s date, --set date: - Set the date.%d: - Day of month (01-31)%h: - Same as %b.%k: - Hour in 24-hour format, without leading zeros (0-23).

    %l: - Hour in 12-hour format, without leading zeros (1-12).%m: - Month of year (01-12).%p: - String to indicate a.m. or p.m.%w: - Day of week (Sunday = 0).%y: - Last two digits of year (00-99).%H: - Hour in 24-hour format (00-23).%I: - Hour in 12-hour format (01-12).

    echo: - Send (echo) the input string to standard output. This is the/bin/echo command.echo also exists as a command built into bash. Thefollowing character sequences have special meanings: (\a)Alert ,(\b)Backspace,(\c) Suppress trailing newline,(\f )Form feed,(\n )Newline,(\r )Carriage return,(\t )Horizontal tab,(\v )Vertical tab,(\\ )Literal backslash,(\nnn )The octal character whose ASCII code is nnn.

    Syntax : - echo [options] [string]Option :- -e :- Enable character sequences with special meaning.-E :- Disable character sequences with special meaning.

  • 7/29/2019 ULP Lab Practical.doc

    17/54

    rm: - Delete one or more files. To remove a file, you must have writepermission in the directory that contains the file, but you need not havepermission on the file itself. If you do not have write permission on the file,you will be prompted (y or n) to override. rm is often aliased to rm -i,

    especially for the root user, to protect against inadvertently deleting files.Syntax: - rm [options] filesOptions: - -d, --directory :- Remove directories, even if they are notempty.-f, --force :- Remove write-protected files without prompting.-i, --interactive :- Prompt for y (remove the file) or n (do not remove the file).

    uname: - Print information about the machine and operating system. Withoutoptions, print the name of the kernel (Linux).

    Syntax: -uname [options]Options: - -a,--all:-Combine all system information from the other options.-i, --hardware-platform :- Print the system's hardware platform.-m, --machine :- Print name of the hardware that the system is running on.-n, --nodename :- Print the machine's hostname.-o, --operating-system :- Print the operating system name.-p, --processor :- Print the type of processor.-r, --kernel-release :- Print the release number of the kernel.

  • 7/29/2019 ULP Lab Practical.doc

    18/54

    ls: - List contents of directories. If no names are given, list the files in thecurrent directory. With one or more names, list files contained in a directoryname or that match a file name. names can include filenamemetacharacters. The options let you display a variety of in formation in

    different formats. The most useful options include -F, -R, -l, and -s. Someoptions don't make sense together (e.g., -u and -c).

    Syntax : - ls [options] [names]Options :- -1, --format=single-column :- Print one entry per line ofoutput.-a, --all :- List all files, including the normally hidden files whose namesbegin with a period..-d, --directory :- Report only on the directory, not its contents.-f :- Print directory contents in exactly the order in which they are stored,without attempting to sort them.

    -h :- Print sizes in kilobytes and megabytes.-i, --inode :- List the inode for each file.-l, --format=long, --format=verbose :- Long format listing (includespermissions, owner, size, modification time, etc.).-r, --reverse :- List files in reverse order (by name or by time).-s, --size :- Print file size in blocks.-x, --format=across, --format=horizontal :- List files in rows goingacross the screen.-R, --recursive :- List directories and their contents recursively.

  • 7/29/2019 ULP Lab Practical.doc

    19/54

    chmod: - Change the access mode (permissions) of one or more files. Onlythe owner of a file or a privileged user may change the mode. mode can benumeric or an expression in the form of who opcode permission. who isoptional (if omitted, default is a); choose only one opcode. Multiple modesare separated by commas.

    Syntax: - chmod [options] mode files chmod [options]--reference=filename filesOptions: - -f, --silent, --quiet :- Do not notify user of files that chmodcannot change.-R, --recursive :-Traverse subdirectories recursively, applying changes.-v, --verbose :- Print information about each file, whether changed or not.

    Whou :- User.g :- Group.o :- Other.a :- All (default).

    Opcode+ :- Add permission.- :- Remove permission.

  • 7/29/2019 ULP Lab Practical.doc

    20/54

    = :- Assign permission

    Permissionsr :- Read.w :- Write.x :- Execute.

    s :- Set user (or group) ID.t :- Sticky bit; used on directories to prevent removal of files by

    non-owners.u :- User's present permission.g :- Group's present permission.o :- Other's present permission.

    Alternatively, specify permissions by a three-digit octal number. The firstdigit designates owner permission; the second, group permission; and thethird, other's permission. Permissions are calculated by adding the followingoctal values:

    4 :- Read.2 :- Write.1 :- Execute.

    Note that a fourth digit may precede this sequence. This digit assigns thefollowing modes:4 :- Set user ID on execution to grant permissions to process based on thefile's owner, not on permissions of the user who created the process.2 :- Set group ID on execution to grant permissions to process based on thefile's group, not on permissions of the user who created the process.

    1 :- Set sticky bit.

    chown: - Change the ownership of one or more files to newowner.newowner is either a user ID number or a login name located in /etc/passwd.chown also accepts users in the form newowner:newgroup ornewowner.newgroup. The last two forms change the group ownership aswell. If no owner is specified, the owner is unchanged. With a period or colonbut no group, the group is changed to that of the new owner. Only thecurrent owner of a file or a privileged user may change the owner.

    Syntax: - chown[options]newowner files chown [options]--reference=filename filesOptions: - -f, --silent, --quiet :- Do not print error messages about filesthat cannot be changed.-v, --verbose :- Print information about all files that chown attempts tochange, whether or not they are actually changed.-R, --recursive :-Traverse subdirectories recursively, applying changes.

    chgrp: - Change the group of one or more files to newgroup. newgroup iseither a group ID number or a group name located in /etc/group. Only theowner of a file or a privileged user may change the group.

  • 7/29/2019 ULP Lab Practical.doc

    21/54

    Syntax: - chgrp [options] newgroup fileschgrp [options]Options: - -f, --silent, --quiet :- Do not print error messages aboutfiles that cannot be changed.-R, --recursive :-Traverse subdirectories recursively, applying changes.

    cp: -Copy file1 to file2, or copy one or more files to the same names under

    directory. If the destination is an existing file, the file is overwritten; if thedestination is an existing directory, the file is copied into the directory (thedirectory is not overwritten).

    Syntax: - cp [options] file1 file2 cp [options] files directoryOptions: - -a, --archive :- Preserve attributes of original files wherepossible.-f, --force :- Remove existing files in the destination.-i, --interactive :- Prompt before overwriting destination files.-r, -R, --recursive :- Copy directories recursively.

    HOME: - Show the home directory, where users personal files are stored.Syntax: - $HOMEpwd :-Print the full pathname of the current working directory.Syntax: - pwdclear: - Clear the terminal display. Equivalent to pressing Ctrl-L.Syntax :- clearmv: -The mv command is often aliased as mv -i in the .bashrc file,especially for the root account, to prevent inadvertently overwriting files.

    Syntax: - mv[file][file2]Options: - -b :- Back up files before removing.-f, --force :- Force the move, even if target file exists; suppress messages

    about restricted access modes.-i, --interactive :- Query user before removing files.-u, --update :- Do not remove a file or link if its modification date is thesame as or newer than that of its replacement.

    mkdir: - Create one or moredirectories. You must have write permissionin the parent directory in order to create a directory. See also rmdir. Thedefault mode of the new directory is 0777, modified by the system or user'sumask.

    Syntax: - mkdir [options] directoriesOptions: --m , --mode mode :- Set the access mode for new directories.-p, --parents :- Create intervening parent directories if they don't exist.

    -v, --verbose :- Print a message for each directory created.rmdir: - Delete the named directories (not the contents). directories aredeleted from the parent directory and must be empty (if not, rm -r can beused instead).

    Syntax: - rmdir [options] directoriesOptions: - --ignore-fail-on-non-empty :- Ignore failure to remove non-emptydirectories.

  • 7/29/2019 ULP Lab Practical.doc

    22/54

    -p, --parents :- Remove directories and any intervening parent directories thatbecome empty as a result. Useful for removing subdirectory trees.

    bc : - bc is a language (and compiler) whose syntax resembles that of C,but with unlimited-precision arithmetic. bc consists of identifiers, keywords,and symbols, which are briefly described in the following entries. Examples

    are given at the end. Interactively perform arbitrary-precision arithmetic orconvert numbers from one base to another. Input can be taken from files orread from the standard input.

    Syntax : - bc [options] [files]

  • 7/29/2019 ULP Lab Practical.doc

    23/54

    PRACTICAL NO. 3

    Aim: - Using Bash shell develops simple programs.1. - Write a program to perform the basic arithmetic operation.

    echo "Enter the two no.s"

    read aread becho "Addition is:"expr $a + $b

    echo "Subtraction is:"expr $a - $b

    echo "Multiplication is:"expr $a \* $b

    echo "Division is:"expr $a / $b

    2. - Write a program to calculate the factorial of a number.

    echo "Enter a number"read numi=2fact=1if [ $num -ge 2 ]then

    while [ $i -le $num ]dofact=`expr $fact \* $i`i=`expr $i + 1`done

    fiecho "Factoral of a number is $fact"

  • 7/29/2019 ULP Lab Practical.doc

    24/54

    3. - Write a program to find greatest of three numbers.

    echo "Enter the three numbers"read aread b

    read cif test $a -gt $b -a $a -gt $c;thenecho "First no is greater"elif test $a -lt $b -a $b -gt $c;thenecho "Second number is largest"elseecho "Third number is largest"fi

    4. - Write a program to perform the basic calculator operations.

    echo "Enter two no.s"read aread becho "1 for addition"echo "2 for subtraction"echo "3 for multiplication"echo "4 for division"echo "Enter your choice"read ch

    case "$ch" in1) c=$((a+b))echo "Sum of two no.s is $c";;

    2) c=$((a-b))echo "Subtraction of two no.s is $c";;

    3) c=$((a*b))echo "Mult of two no.s is $c"

    ;;

    4) c=$((a/b))echo "Div of two no.s is $c";;*) echo "Wrong choice"esac

  • 7/29/2019 ULP Lab Practical.doc

    25/54

    5. - Write a program to find a number whether even or odd.

    echo "Enter a number"read numif [ `expr $num % 2` -eq 0 ]

    thenecho "$num is even"elseecho "$num is odd"fi

  • 7/29/2019 ULP Lab Practical.doc

    26/54

  • 7/29/2019 ULP Lab Practical.doc

    27/54

  • 7/29/2019 ULP Lab Practical.doc

    28/54

    PRACTICAL NO. 4

    AIM: -Familiarize with vi editor and Linux GUIs.

    vi editor: - There are three type of editor

    ED

    EX

    VI

    ED and EX are line editor, in this editor line number is assigned to the lines ina file where as vi is the text editor or screen editor. The vi editor has beenpart of UNIX-based systems since the 1970s, and its interface shows it. It isarguably one of the last editors to actually use a separate command mode

    and data entry mode; as a result, most newcomers find it unpleasant to use.The vi editor is difficult to learn at first, but once you know it, you never haveto use a mouse or a function keyyou can edit and move around quickly andefficiently within files just by using the keyboard. It shows as much of the fileas it can fit on screen. It is the first full screen editor which allow the user toview and edit the entire document at a time creating and editing of a filebecomes easy using vi editor.

    Starting vi or say to invoke vi

    To create a file

    Example: - $ vi file.txtTo invoke vi type vi and file name that you want to create when we type viand the file name press enter key then vi clears the screen and display awindow in which we can enter and edit text. The easiest way to learn moreabout vi is to start it and enter :help.

    Mode of operations: - There are three mode of operation of vi editor.

    Command mode: - In this mode we insert text in blank text file orediting in existing text file. Input mode also known as insertion mode.When a key is pressed of input mode it does not appear on screen butsubsequent key depressions do.

    Insertion mode: - In this mode all key passed by user are interpretedto the editor commands that is for moving cursor for left-right top-bottom etc. In this the key pressed are not displayed on screen. Bydefault vi editor in command mode.

    Execute mode: - This mode is used to handle the files and performsubstitutions. It always starts with columns :.

  • 7/29/2019 ULP Lab Practical.doc

    29/54

    Input mode: -

    Insert and append:-i- To insert the text in a file to anywhere.

    I- To insert the text in a file only at the beginning of a line.a- To append the text in file any whereA- To append the text at end of line

    Replace :-r- Replace single terminal character in a files- One character replaced by multiple charactersR- Replace all text on the right of cursor positionS- Replace entire line

    Open line: -o- Line editing at below of current lineO- Line editing at upper of current line

    Execution mode: - These are following command.:w- saves file and remains in editing mode:w viki.txt - Saves to file viki.txt:w! viki.txt - As above, but overwrites exiting file:w >> viki.txt - Appends current file contents to file viki.txt: n1,n4w viki.txt - Writes lines n1 to n4 to file viki.txt:.w viki.txt - Writes current line to file viki.txt

    :$w viki.txt - writes last line to file viki.txt:.,$w viki.txt - writes current to last line to viki.txt:x- saves file and quits editing mode:wq- same as :x:q- quit from editor without saving the buffer:q!- forcefully quit from the editor without saving the buffer:sh- escapes to UNIX shell:recover- recovers file from a crash

    Navigation: - There are several navigation keys for controlling the cursormovement. These are as:

    k- Moves cursor upj- Moves cursor downh- Moves cursor leftl- Moves cursor rightb- Moves back to beginning of worde- Moves forward to end of wordw- Moves forward to beginning of word0(zero) - moving to the beginning of a line

  • 7/29/2019 ULP Lab Practical.doc

    30/54

    |- to position the cursor to certain column$- moves to end of line[Ctrl-f] - Scrolls forward[Ctrl-b] - scrolls backward[Ctrl-d] scrolls half page forward

    [Ctrl-u] - scrolls half page backwardG goes to end of file

    Editing text: - The editing facilities in vi are very elaborate and involvethe use of operators. There are two operators:

    d- Deletey- Yank (copy)

    d and y are not commands, but they can be used for deleting and copyingentire lines. These are following commands for editing operations:

    x- Deletes a single character under the cursor4x-deletes the current character as well as three characters from theright.

    dd- Delete the entire line4dd -deletes the current line and the 3 lines belowyy- Yank the entire line10yy- yanks current line and 9 lines belowp- Puts the data below the current lineP- Puts the data above the current lineJ- Used to join the lines4J-joins following 3 lines with current lineu- To undo the last change madeU- Reverse all change made to the current line

    Repeating the last command:- the vi editor has the facility to repeatthe last command, but most editor do not have. The dot (.) Command is usedfor repeating both Input and Command mode that perform editing tasks.

    Searching for a pattern: -vi is strong in search and replacementactivities. Searching can be made in both forward and reverse directions,and can be repeated. It is initiated from the Command mode by pressing a /,which shows up in last line as :

    / - For forward search? - For backward search

    Command for repeating the last pattern searches are:n- Repeats search in the same direction along which previous search

    was madeN- Repeats search in direction opposite to that along which previous

    search was made

    Substitution: - vi offers yet another powerful feature, that of substation,which is achieved with the ex modes command. The syntax is as:

  • 7/29/2019 ULP Lab Practical.doc

    31/54

    :address/source_pattern/target_pattern/flags

    The source_pattern is replaced with target_pattern in all lines specified byaddress. The address can be one or a pair of numbers, separated by acomma. The most commonly used flag is g, which substitute all occurrences

    of the pattern in a line. For example::1,$s/director/member/g

    The target pattern is optional. If you leave it out, then youll delete alloccurrences of the source pattern in all lines matched by address. Forexample:

    :1,23s/member//g

    Interactive substitution:- something like to selectively replace a string. In thiscase, add the c (confirmatory) parameter as the flag at the end:

    :1,$s/director/member/gc

    Disadvantages: - There are no of self explanatory error message in vi if anything goes

    wrong then there is an error message appear. Only speaker keeps toinform that something wrong

    No help available in vi editor

    There are three mode in which vi editor work but in each mode samekey create different effects

    vi is key sensitive. Vi can handle that maintain plain text that no fstylein fault. No graphic just simple text file we can create, edit and print

  • 7/29/2019 ULP Lab Practical.doc

    32/54

  • 7/29/2019 ULP Lab Practical.doc

    33/54

  • 7/29/2019 ULP Lab Practical.doc

    34/54

  • 7/29/2019 ULP Lab Practical.doc

    35/54

    PRACTICAL NO. 5

    AIM: -Develop some programs using grep and sed. Display the lines containing director.

    Delete those lines whose employ id is two thousand.

    Count the lines containing manager as designation.

    Display the line number record having sales as Department.

    Display the lines where salary lies between 80000-89999.

    Replace the manager with executive.

    Replace pipe symbol with colon symbol in the emp.lst.

    Add prefix e to all employ ids.

    Grep: -UNIX has a special family of commands for handling search requirements,and grep is the principal member of this family. It scans a file for the occurrence ofa pattern and, depending on the options used, display

    Lines containing the selected pattern.

    Lines not containing the selected pattern (-v).

    Lines number where the pattern occurs (-n).

    Number of lines containing the pattern (-c).

    Filenames where the pattern occurs (-l).

    Grep is exceedingly simple to use too. Its syntax treats the first argument as thepattern and the rest as filenames.

    Syntax: -grep options pattern filename(s)

    Sed: - Sed is a multipurpose tool which combines the work of severalfilters. Sed is designed by Lee McMahon. Sed is derived from the ed lineeditor, the original editor of UNIX. Sed is used for noninteractive operations.It acts on data stream.

  • 7/29/2019 ULP Lab Practical.doc

    36/54

    Sed has very few options. It has numerous features almost bordering on aprogramming language. Due to obvious constraints, we shall have to stop ofits limits because its functions have been taken over by perl. Perl oftenhandle them better and faster.Everything in sed is an instruction. An instruction combines an address for

    selecting lines with an action to be taken on them.

    Syntax:sed options address action file(s)

    The address and action are enclosed within single quotes. The actioncomponent is drawn from sed family of internal command. It can either be asimple display or an editing function like insertion deletion or substitution oftext.

    Solution: -grep director emp.lstgrep -v ^5000 emp.lst > emp2.lstgrep -n manager emp.lstgrep -c sales emp.lstgrep 8.$ emp.lstsed s/manager/executive/ emp.lstsed s/|/:/g emp.lstsed s/^/e/ emp.lst

  • 7/29/2019 ULP Lab Practical.doc

    37/54

  • 7/29/2019 ULP Lab Practical.doc

    38/54

  • 7/29/2019 ULP Lab Practical.doc

    39/54

    PRACTICAL N0. 6

    AIM: - Develop advanced shell programs using awk.

    First, we create a table including empid, name, designation, department andbasic pay.

    Awk :- It is similar to find and sed.The awk command combines thefunctions of grep and sed, making it one of the most powerful Unixcommands. Using awk, you can substitute words from an input file's lines forwords in a template or perform calculations on numbers within a file. Thecommand uses the following syntax :awk options selection_criteraia (action) filename(s)The selection_criteria filters input and selects lines.{ print } = whitespace permitted.

    { print $0} = $0 is the complete lines.

    Programs :-A). Display name, designation of all employees belonging to marketingdepartment.B). Write a program to count manager drawing salary exceeding 7000.C). Write a program to calculate average basic pay of the employees havingsalary greater than 8000.

  • 7/29/2019 ULP Lab Practical.doc

    40/54

    D). Write program to calculate average basic pay , average hra, average daand total salary of the employees belonging to sales or marketingdepartment.

    emp.awk :-

    BEGIN {printf "\t\tEmployee abstract\n\n"} $5 > 7500 {kount++ ; tot+= $5printf "%3d %-20s %-12s %d\n", kount,$2,$3,$5}END {printf "\n\tThe average basic pay is %6d\n", tot/kount}

    Emp2.awk :-

    BEGIN {FS = "|"printf "%42s\n", "Basic Da Hra Gross"} /sales|marketing/ {da = 0.25*$5 ; hra = 0.50*$5 ; gp = $5+hra+datot[1] += $5 ; tot[2] += da ; tot[3] += hra ; tot[4] += gpkount++}END {printf "\t Average %5d %5d %5d %5d\n", \tot[1]/kount, tot[2]/kount, tot[3]/kount, tot[4]/kount}

  • 7/29/2019 ULP Lab Practical.doc

    41/54

    PRACTICAL NO. 7

    AIM- Compile and debug various C programs using different

    options.

    GCCThe GNU Compiler Collection (GCC) is by far the most dominant compiler(rather, the mostdominant collection of compilers) used on Linux systems. It compilesprograms written in C, C++,Objective-C, Fortran, Java, and Ada.

    GCC gives programmers extensive control over the compilation process. Thatprocess includesup to four stages: preprocessing, compilation, assembly, and linking. You canstop the processafter any of these stages to examine the compilers output at that stage.GCC can also handle thevarious C dialects, such as ANSI C or traditional (Kernighan and Ritchie) C.You can control theamount and type of debugging information, if any, to embed in the resultingbinary. And as with

  • 7/29/2019 ULP Lab Practical.doc

    42/54

    most compilers, GCC also performs code optimization.

    The gcc command invokes the C compiler. To use it, provide it the name of aC source file anduse its -o option to specify the name of the output file. gcc will preprocess,

    compile, assemble,and link the program, generating an executable, often called a binary.

    Syntax: -gcc infile.c [-o outfile]

    infile.c is a C source code file and -o says to name the output file outfile. The[] charactersindicate optional arguments. If the name of the output file is not specified,gcc names the output file a.out by default. Not all steps need to be handledby the gcc program

    itself, as gcc can hand off processing tasks such as linking to ld, the GNUlinker.

    Compile program with gcc: -$ gcc ulp7$ ./a.out$ gcc o ulp7 ulp7.c$ ./ulp7

    Warnings: -$ gcc Wall o ulp7 ulp7.c

    $ gcc Wall -Werror o ulp7 ulp7.c

    Optimization with gcc: -$ time ./ulp7$ gcc Wall O1 o ulp7 ulp7.c$ time ./ulp7

    Debugging with gcc: -$ gcc g Wall o ulp7 ulp.c$gcc ggdb3 Wall o ulp7 ulp7.c$ gdb ulp7(gdb)break main(gdb)run(gdb)step(gdb)quit

  • 7/29/2019 ULP Lab Practical.doc

    43/54

  • 7/29/2019 ULP Lab Practical.doc

    44/54

  • 7/29/2019 ULP Lab Practical.doc

    45/54

  • 7/29/2019 ULP Lab Practical.doc

    46/54

    PRACTICAL NO. 8

    Aim: - Create a simple make file and smarter make file.

    GNU Make: -As your programs get larger, the process necessary to build them becomesmore complex and time-consuming. The Linux environment provides a toolto help you with this process: GNU make.A Makefile is nothing more than a collection of rules. A rule consists offollowing things: -

    Target : - The thing make ultimately tries to create

    Dependencies: - A list of one or more dependencies (usually files)required to build the target

    Commands: - A list of commands to execute to create the target from

    the specified dependenciesDependencies arent necessarily the files that are built. They can be otherarbitrary files. For instance, a C program might list an include file as adependency. This means that if the include file is updated, the C file will berecompiled to take into account the changes

    Smarter makefile: - You can use variables in your Smarter Makefile. Thisnot only reduces the typing (and possible errors) necessary to create yourrules, but also enables you to change the rules throughout the entire file bymodifying one or two lines. This can be a big win for large files.Setting variables in a Makefile is similar to doing the same in Bash; you use

    the equals sign (=) to separate the variable name, on the left, from the newvalue on the right. To access the contents of the variable later, the syntax isslightly different. With make, you use $(VARIABLE) to access the contents ofthe variable named VARIABLE.

    Intelligent Makefiles that can automatically detect many things abouttheir environment so that you often dont need to tell them even the namesof the files that comprise your program!

    For compute.c, the source is: -extern int someglobal;int computer(void){

    return 5 * someglobal;}

    For init.c, the source is: -#include

  • 7/29/2019 ULP Lab Practical.doc

    47/54

    #include myprogram.hint someglobal = 11;int main(void){

    foo();

    return 0;}

    For io.c, the source is: -#include #include myprogram.hint foo(void){

    printf(The value is: %d.\n, computer());return 1;

    }

    For the header file, myprogram.h, the source is: -int computer(void);int foo(void);

    Code for makefile: -all: myprogram.myprogram: io.o init.o compute.o

    gcc -o myprogram io.o init.o compute.ocompute.o: compute.c

    gcc -Wall -c -o compute.o compute.c

    init.o: init.c myprogram.hgcc -Wall -c -o init.o init.c

    io.o: io.c myprogram.hgcc -Wall -c -o io.o io.c

    Code for smarter makefile: -CC=gccCFLAGS=-WallCOMPILE=$(CC) $(CFLAGS) call: myprogrammyprogram: io.o init.o compute.o

    $(CC) -o myprogram io.o init.o compute.oinit.o io.o: myprogram.h%.o: %.c

    $(COMPILE) -o $@ $

  • 7/29/2019 ULP Lab Practical.doc

    48/54

  • 7/29/2019 ULP Lab Practical.doc

    49/54

    Experiment No: - 9

    Aim: -To create a smarter makefile.

    Smarter makefile: - You can use variables in your Smarter Makefile. Thisnot only reduces the typing (and possible errors) necessary to create yourrules, but also enables you to change the rules throughout the entire file bymodifying one or two lines. This can be a big win for large files.Setting variables in a Makefile is similar to doing the same in Bash; you usethe equals sign (=) to separate the variable name, on the left, from the newvalue on the right. To access the contents of the variable later, the syntax isslightly different. With make, you use $(VARIABLE) to access the contents ofthe variable named VARIABLE.

    Code for smarter makefile: -CC=gccCFLAGS=-WallCOMPILE=$(CC) $(CFLAGS) call: myprogrammyprogram: io.o init.o compute.o

    $(CC) -o myprogram io.o init.o compute.oinit.o io.o: myprogram.h%.o: %.c

    $(COMPILE) -o $@ $

  • 7/29/2019 ULP Lab Practical.doc

    50/54

    Experiment No: - 10

    Aim:- Learning of installation and upgradation of Linux operatingsystem.

    Theory: -Installing Linux on a personal computer may not be as difficult asyou think. This document explains how to install Linux on a PC, starting at

    the beginning: choosing a distributionThe first step for setting up Linux on a PC is the most time consuming, it issimply to use a run from CD version of all distributions that you areinterested in to pick the version you want to install. Once you pick thedistributions you want to check out, go to the distribution's Web sites anddownload the live CD/move ISO image for it. Then, using the method for yourCD burning software, burn the ISO image to CDROM. With the CDROM in thedrive, reboot the computer and you are now running the Linux version.Once you have selected which distribution(s) you will install, you can go backto that distribution's Web site and download the install version of thedistribution, which is most commonly made up of three CDROM ISO images.

    After these are downloaded, burn the ISO images to CDROM.Delete the images from your hard drive after burning them to CDs.You will then have to decide, before going any further, if you wish to multi-boot and keep Windows on the system. If you are going to keep Windows,you will have to run a defragmenting utility on the drive before going anyfurther.Completely cleaning up your hard drive, removing all temp files anddefragmenting it before backing up the data is always a good idea, and

  • 7/29/2019 ULP Lab Practical.doc

    51/54

    backing up your system is recommended before installing a new operatingsystem. Because Microsoft's NTFS is not 100 percent supported, this is evenmore important if you are running any NT-based version of Windows.If you have chosen to use a "Boxed set" of Linux, there is a set of "DOS" toolson one of the CDs, which will run in Windows and allow you to resize the

    partition for Windows. If you are using a downloaded version, then you canuse the Linux tools during installation, but you may have to completelydelete the Windows partition. Getting a trial version of Partition magic willallow you to resize the Windows partition without losing the data.The partition table structure for a multi boot system looks complex, at first,but is actually very simple:

    The first primary partition is your Windows partition. The first extended partition is a transfer partition for enabling

    read/write access to files from all operating systems, and needs to beeither a FAT32 partition or a FAT16 partition

    The second extended partition is the first Linux partition, and should be

    set up in the Linux installation process. For only Windows and oneLinux version, a 500MB partition is more than enough room. It will begiven the label of /boot [500MB in size ]

    You will need to create a partition with the label / [5 GB in size] Create a partition with the label /home [remaining amount of space for

    distribution] Create a partition with the label /usr [5 GB in size] Create a partition with the label /var [1 or 2 GB in size] Create a partition with the label /swap [double your RAM in size]

    When creating the partitions you will notice that you have a number of filesystem type options; the oldest one being the ext2fs. In a graphic installer,

    the file system types usually have an explanation of what they mean. Thecurrent default file system is the reiserfs, a journaled file system. This has asmall hit on speed, but a major improvement on data protection, comparedto a non journaled file system.Speed and reliability for data input/output being important, the reiserfs orthe ext3fs are the best supported file systems. If speed is more importantthan reliability, use the ext2fs. This does not mean major risk of data loss,but power fluctuations may cause some data loss or corruption, if you havespotty power, and do not have an interruptible power supply, go with ajournalized file system.Follow the prompts for the distribution you are installing. Each distribution

    has a different installation process, so detailing them here is not a viableoption. If you are using one with a console /text interface, the space barselects, and the right arrow will expand a category, the left arrow willcollapse a category, up and down arrows will move you up and down in thelisting. The enter key will finish the selection process and start theinstallation. A graphic interface installation program will have mousesupport.Selecting a package

  • 7/29/2019 ULP Lab Practical.doc

    52/54

    Package selection is a big part of installing Linux. When first trying Linux itdoesn't hurt to install everything, as this enables you to see whichapplications you like and will use. There are far more options than the liveCD versions can include, so while you have some idea about packages fromhaving looked at the live CD, there are more options than those shown.

    Generally, there are over 10 thousand packages in a three CD version of adistribution, including the libraries for software development.You may see a message screen after you have selected, or during theselection process, that lists a number of packages. This is a list of packagesrequired by the one you just selected, called dependencies; you can just hitthe ok button when you see it. Some installers allow for this notification to beturned off, which I would recommend against, as the dependencies will helpyou to see the different parts of each application.During the installation you will be presented with a series of configurationoptions. The four most important ones are:

    The firewall--you should turn it on, and at this time you can choose

    what traffic will be allowed incoming from the Internet, if any. The Display settings--this will configure the graphic server for the

    GUI, and you should use the test configuration option when doing this. The mouse--it is a good idea to specify which connection and type, as

    the any USB or PS2 default of many distributions is not always areliable mouse driver.

    The Internet connection--if you connect through a network card,then configure it as a network connection, not a DSL connection, evenif you use DSL.

    If you tell Linux it's a DSL connection then Linux looks for the DSL modem asa device in the computer and you will not get online. If you use dial up

    connection, and your modem is classed as a Winmodem, then you will needto get the drivers for it from the linmodems Web site before installing Linux.After installing Linux, you will have to compile the drivers for the modem,install them and run the network configuration tool for the distribution youhave installed.Boot loaderWhen the boot loader is installing, you have the option of setting which bootloader to use, GRUB or LILO, either is a stable option. You can also set whichOS will be the default OS at boot. The screens will have a default box onthem, if you wish to keep Windows as default then just select default whenhighlighting Windows (note, it may be DOS with some distributions). You can,

    if you want, delete the failsafe and nonframebuffer boot options, keepingonly Linux, Windows and floppy options. (Note, the floppy option is notalways included with newer distributions).If you are installing several versions of Linux, the boot partition createdduring the first Linux installation will need to be selected and labelled as/boot for each one. Make the same partitions for each version, except forswap, that you only need one. Do NOT use any other pre-existing Linuxpartition with different distributions, as the versions of software between the

  • 7/29/2019 ULP Lab Practical.doc

    53/54

    distros may cause conflicts when booting into them. By using the same bootpartition, the bootloader installation step will read the data in it andconfigure the multi-boot for each new distribution. It may be useful to labeleach distro by its name in the boot menu as you go, this will make the bootoptions clearer when you are choosing one.

    When updating the Red Hat EL or SLES operating system on nodes, if theMode attribute is PreManaged, then after the operating system upgrade,the Mode attribute value is changed to Managed. If the Mode attribute isManaged, then it is not changed. If the Mode attribute is MinManagedbefore the operating system upgrade, then the Mode attribute value remainsMinManaged.If the installnode command fails for a PreManaged node, the attributevalue of the node is PreManaged or Installing. If the installnodecommand fails for a MinManaged node, the attribute value of the node isMinManaged or MinManaged-Installing .To upgrade the operating system and CSM on all the nodes, issue the

    following command:installnode -aThe Red Hat EL nodes with the InstallMethod attribute set to kickstart-upgrade are rebooted and upgraded with the new level of the operatingsystem, rebooted, and then CSM is updated if necessary. The Red Hat ELoperating system upgrade runs asynchronously. Immediately after theoperating system upgrade process is initiated (that is, when the node isrebooted), the installnode command exits, even though the operatingsystem upgrade is not complete.The SLES nodes with the InstallMethod attribute set to you are updated withthe new level of the operating system, rebooted to pick up the new kernel,

    and then CSM is upgraded if necessary. The installnode commandcontinues to run as the SLES operating system is updated. This may take awhile to run. Then, installnode reboots the node, and exits. The rest of theupgrade process (CFM, SMS, osupgradepostreboot scripts, upgradingCSM) continues asynchronously.You can use the -t flag on the installnode command to provide a timeoutvalue in minutes. If you do not specify a value for timeout, the default is 60minutes:installnode -P -t timeoutIf the operating system upgrade process does not complete within thetimeout period specified, CSM considers the operating system upgrade

    process as failed. You can use the monitorinstall command to provide outputinformation for the installation process.After the operating system is updated, the following jobs run on the node:

    1. The osupgradeprereboot customization scripts are run.2. The node reboots to its local hard disk.3. CSM is installed, along with the software listed in Planning for CSM for

    Linux.

    http://publib.boulder.ibm.com/infocenter/clresctr/vxrx/topic/com.ibm.cluster.csm16010.install.doc/am7il_softreq.html#softreqhttp://publib.boulder.ibm.com/infocenter/clresctr/vxrx/topic/com.ibm.cluster.csm16010.install.doc/am7il_softreq.html#softreqhttp://publib.boulder.ibm.com/infocenter/clresctr/vxrx/topic/com.ibm.cluster.csm16010.install.doc/am7il_softreq.html#softreqhttp://publib.boulder.ibm.com/infocenter/clresctr/vxrx/topic/com.ibm.cluster.csm16010.install.doc/am7il_softreq.html#softreq
  • 7/29/2019 ULP Lab Practical.doc

    54/54

    4. The node's Mode attribute changes to Managed, or remainsMinManaged.

    5. SSH or RSH are set up on the node so that the node is accessible fromthe management server.

    6. Any CFM files are transferred to the node.

    7. SMS is run to install or update software, if it is configured.8. The osupgradepostreboot customization scripts are run.If you defined Kerberos options with the csmconfig command when youdefined the management server, the installnode command sets up theKerberos options for the cluster..After an operating system upgrade the node BIOS boot order can remain:

    1. diskette2. CD-ROM3. network4. hard disk

    Every time the node boots, it uses Dynamic Host Configuration Protocol

    (DHCP) to contact the management server or install server, which usespxelinux to boot the node from its hard drive. Alternately, after theoperating system upgrade is complete, you can change the boot order in theBIOS to the following:

    1. diskette2. CD-ROM3. hard disk4. network