Sie sind auf Seite 1von 55

Linux Manual

LINUX COMMANDS
Ex No: 1
Aim: To Write a commands to execute the following. a) Logon to Unix and Logoff b) Directory Management commands c) File Management commands

Logon, Logoff Directory & File Management

COMMANDS: (a) Logon to UNIX and logoff Log In To login, enter your username where prompted, hit the Return or Enter key, then enter your password and hit the Return key again. Here is a sample session. Syntax: Username : root Password : ********

Log Off You need to know how to end your Unix session by logging off. To log off, just issue the exit command. Syntax: $ exit Your Unix window should go away. If not, try the command logoff or logout. Or try pressing the control and D keys on your keyboard simultaneously.

b) Directory management Commands Creating and Deleting Directories mkdir Short for make directory this command is used to create a new directory. Syntax mkdir [option] directory

M.S.P.V.L.Polytechnic College

Page 1

Linux Manual
Options: -m mode -p -v -Z directory - Set permission mode (as in chmod), not rwxrwxrwx - umask. - No error if existing, make parent directories as needed. - Print a message for each created directory - (SELinux) set security context to CONTEXT - The name of the directory that you wish to create.

Output [root @sample root]# mkdir mydir [root @sample mydir]# cd

rmdir Deletes a directory.

Syntax rmdir [OPTION]... DIRECTORY...

Options: -- (ignore-fail-on-nonempty) -p ( --parents) ignore each failure that is solely because a directory is non-empty. Remove DIRECTORY and its ancestors. E.g., `rmdir -p a/b/c' is similar to `rmdir a/b/c a/b a'. -v ( --verbose) --version output a diagnostic for every directory processed. output version information and exit.

Output [root @sample root]# ls 1 anaconda-ks.cfg f2 f3 addn copy jey Greet1 john mydir

[root @sample root]# rmdir john [root @sample root]# ls 1 ls Lists the contents of a directory anaconda-ks.cfg f1 f2 f3 addn copy jey Greet1

M.S.P.V.L.Polytechnic College

Page 2

Linux Manual
Syntax: ls [options] [names]

Options: -a -A only. -b -c -C -d -f -F - Show nonprinting characters in octal. - List files by inode modification time. - List files in columns (the default format, when displaying to a terminal device). - List only the directory's information, not its contents. (Most useful with -l and -i.) - Interpret each name as a directory (files are ignored). - Flag filenames by appending / to directories, > to doors (Solaris only), * to executable files, | to fifos, @ to symbolic links, and = to sockets. -g -i -l -L -m -n -o -p -q -r -R -s -t -u -x -1 - Like -l, but omit owner name (show group). - List the inode for each file. - Long format listing (includes permissions, owner, size, modification time, etc.). - List the file or directory referenced by a symbolic link rather than the link itself. - Merge the list into a comma-separated series of names. - Like -l, but use user ID and group ID numbers instead of owner and group names. - Like -l, but omit group name (show owner). - Mark directories by appending / to them. - Show nonprinting characters as ?. - List files in reverse order (by name or by time). - Recursively list subdirectories as well as current directory. - Print sizes of the files in blocks. - List files according to modification time (newest first). - List files according to the file access time. - List files in rows going across the screen. - Print one entry per line of output. - List all files, including the normally hidden . files. - Like -a, but exclude . and .. (the current and parent directories). Solaris

Output: [root @sample root]# ls 1 anaconda-ks.cfg Greet1 [root @sample root]# cd Changes the directory.
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 3

f1

f2

f3

addn copy jey

Linux Manual
Syntax cd [directory] Options: Directory cd .. Name of the directory user wishes to enter. Used to go back one directory on the majority of all Unix shells. It is important that the space be between the cd and the .. cd When in a Korn shell to get back one directory used to go back one directory. Output [root @sample mydir]# cd john [root @sample john]# pwd(Print working directory) Short for print working directory the pwd command displays the name of the current working directory.

Syntax pwd

Output [root @sample root]# pwd /root c)File Management Commands cat Allows you to look, modify or combine a file. Syntax cat filename [-n] [-b] [-u] Options: filename -n -b -u -s -v The name of the file or files that you wish to look at or perform tasks on. Precede each line output with its line number. Number the lines, as -n, but omit the line numbers from blank lines. The output is not buffered. (The default is buffered output.) cat is silent non-existent files. Non-printing characters (with the exception of tabs, new-lines and formfeeds) are printed visibly. ASCII control characters (octal 000 - 037) are printed as ^n, where n is the corresponding ASCII character in the range
M.S.P.V.L.Polytechnic College Page 4

Linux Manual
octal 100 - 137 (@, A, B, C, . . ., X, Y, Z, [, \, ], ^, and _); the DEL character (octal 0177) is printed ^?. Other non-printable characters are printed as M-x, where x is the ASCII character specified by the low order seven bits. -e A $ character will be printed at the end of each line (prior to the newline). -t Tabs will be printed as ^I's and form feeds to be printed as ^L's.

Output [root @sample root]# cat f1 f3 > f9 [root @sample root]# ls 1 anaconda-ks.cfg f1 f2 f3 addn copy jey

Greet1 f9

chmod Changes the permission of a file.

Syntax chmod [OPTION]... MODE[,MODE]... FILE... chmod [OPTION]... OCTAL-MODE FILE... chmod [OPTION]... --reference=RFILE FILE... Options: -c, --changes --no-preserve-root --preserve-root -f, --silent, --quiet -v, verbose --reference=RFILE -R, --recursive --help --version Permissions: u g o a r w x - User who owns the file. - Group that owns the file. - Other. - All. - Read the file. - Write or edit the file. - Execute or run the file as a program.
Page 5

like verbose but report only when a change is made do not treat `/' specially (the default) fail to operate recursively on `/' suppress most error messages output a diagnostic for every file processed use RFILE's mode instead of MODE values change files and directories recursively display this help and exit output version information and exit

M.S.P.V.L.Polytechnic College, Pavoorchatram

Linux Manual
Numeric Permissions: CHMOD can also to attributed by using Numeric Permissions: 400 read by owner 040 read by group 004 read by anybody (other) 200 write by owner 020 write by group 002 write by anybody 100 execute by owner 010 execute by group 001 execute by anybody Output: [root @sample root]# chmod 644 f9 [root @sample root]# ls -l -rw-rr--rw-rr--rw-rr-cp Copies files from one location to another. Syntax cp [OPTION]... SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... --targetdirectory=DIRECTORY SOURCE... Options: -a, --archive --backup[=CONTROL] -b --copy-contents -d --no-dereference -f, --force - same as -dpR - make a backup of each existing destination file - like --backup but does not accept an argument - copy contents of special files when recursive - same as --no-dereference --preserve=link - never follow symbolic links - if an existing destination file cannot be opened, remove it and try again -i, --interactive -H -l, --link -L, --dereference
M.S.P.V.L.Polytechnic College

1 1 1

root root root

root root root

37 May 18 15:38 f9 518 Mar 22 12:22:22 greet1 8 May 18 12:13:16 f2

- prompt before overwrite - follow command-line symbolic links - link files instead of copying - always follow symbolic links
Page 6

Linux Manual
-p --preserve[=ATTR_LIST] - same as --preserve=mode,ownership,timestamps - preserve the specified attributes (default: mode,ownership,timestamps), if possible additional attributes: links, all --no-preserve=ATTR_LIST --parents -P -R, -r, --recursive --remove-destination don't preserve the specified attributes append source path to DIRECTORY

- same as '--no-dereference' - copy directories recursively - remove each existing destination file before attempting to open it (contrast with --force)

--reply={yes,no,query}

- specify how to handle the prompt an existing destination file

--sparse=WHEN --strip-trailing-slashes

- control creation of sparse files - remove any trailing slashes from each SOURCE argument

-s, --symbolic-link -S, --suffix=SUFFIX --target directory=DIRECTORY -u, --update

- make symbolic links instead of copying - override the usual backup suffix move all SOURCE arguments into DIRECTORY

- copy only when the SOURCE file is newer than the destination file or when the destination file is missing

-v, --verbose -x, --one-file-system

- explain what is being done - stay on this file system

Output: [root @sample root]# cp f3 f10 [root @sample root]# ls 1 anaconda-ks.cfg f10 f1 f2 f3 addn copy jey Greet1 f9

rm Deletes a file without confirmation (by default).

Syntax rm [-f] [-i] [-R] [-r] [filenames |

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 7

Linux Manual
Options: -f Remove all files (whether write-protected or not) in a directory without prompting the user. In a write-protected directory, however, files are never removed (whatever their permissions are), but no messages are displayed. If the removal of a write-protected directory is attempted, this option will not suppress an error message. -I Interactive. With this option, rm prompts for confirmation before removing any files. It over- rides the -f option and remains in effect even if the standard input is not a terminal. -R -r Same as -r option. Recursively remove directories and subdirectories in the argument list. The directory will be emptied of files and removed. The user is normally prompted for removal of any write-protected files which the directory contains. The write-protected files are removed without prompting, however, if the -f option is used, or if the standard input is not a terminal and the -i option is not used. Symbolic links that are encountered with this option will not be traversed. If the removal of a non-empty, writeprotected directory is attempted, the utility will always fail (even if the -f option is used), resulting in an error message. Filenames Output [root @sample root]# rm f10 Rm: remove regular file f10? Y [root @sample root]# ls 1 anaconda-ks.cfg mv Renames a file or moves it from one directory to another directory. Syntax mv [-f] [-i] oldname newname Options: -f mv will move the file(s) without prompting even if it is writing over an existing target. Note that this is the default if the standard input is not a terminal. -i oldname Prompts before overwriting another file. The oldname of the file renaming. f1 f2 f3 addn copy jey Greet1 f9 A path of a filename to be removed.

M.S.P.V.L.Polytechnic College

Page 8

Linux Manual
newname The newname of the file renaming. filename The name of the file you want to move directory - The directory of were you want the file to go.

Output [root @sample root]# mv f3 f11 [root @sample root]# ls 1 anaconda-ks.cfg more Displays text one screen at a time. Syntax more [-c] [-d] [-e] [-f] [-i] [-l] [-n number] [-p command] [-r] [-s] [-t tagstring] [-u] [-w] [ -lines ] [ + linenumber ] [ +/ pattern ] [ file ... ] Options: -c Clear before displaying. Redraws the screen instead of scrolling for faster displays. This option is ignored if the terminal does not have the ability to clear to the end of a line. -d Display error messages rather than ringing the terminal bell if an unrecognized command is used. This is helpful for inexperienced users. -e Exit immediately after writing the last line of the last file in the argument list. -f Do not fold long lines. This is useful when lines contain nonprinting characters or escape sequences, such as those generated when nroff output is piped through ul. -i -l -n number Perform pattern matching in searches without regard to case. Ignores form-feed characters (Ctrl + L starts the new page.) Specify the number of lines per screenful. The number argument is a positive decimal integer. The -n option overrides any values obtained from the environment. -p command For each file examined, initially execute the more command in the command argument. If the command is a positioning command, such as a line number or a regular expression search, set the current position to represent the final results of the command, without writing any intermediate lines of the file. -r Displays control keys.
Page 9

f1

f2

f11

addn copy jey

Greet1 f9

M.S.P.V.L.Polytechnic College, Pavoorchatram

Linux Manual
-s -t tagstring Doesn't display extra blank lines. Write the screenful of the file containing the tag named by the tagstring argument. -u -w Ignores backspace and underscores. Normally, more exits when it comes to the end of its input. With w, however, more prompts and waits for any key to be struck before exiting. -lines Display the indicated number of lines in each screenful, rather than the default (the number of lines in the terminal screen less two). +linenumber +/pattern filename Output: [root @sample root]# more +3 f11 file Tells you if the object you are looking at is a file or if it is a directory. Start up at linenumber Displays text two lines before the first time text appears. The name of the file.

Syntax file [-c] [-h] [-m mfile] [-f ffile] names Options: -c Check the magic file for format errors. For reasons of efficiency, this validation is normally not carried out. -h -m mfile -f ffile names Output: [root @sample root]# vi a.txt [root @sample root]#file *.txt a.txt : ASCII text Do not follow symbolic links. Use mfile as an alternate magic file. ffile contains a list of the files to be examined. Specifies the directories of files that you want the information .

Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College

Page 10

Linux Manual Ex No: 2


Aim: Write a Linux commands to understand the use of general purpose commands. COMMANDS : who Displays who is on the system. Syntax who [-a] [-b] [-d] [-H] [-l] [-m] [-nx] [-p] [-q] [-r] [-s] [-t] [-T] [-u] [am i] [ file ] Options: -a Process /var/adm/utmp or the named file with -b, -d, -l, -p, -r, -t, -T, and -u options turned on. -b -d Indicate the time and date of the last reboot. Display all processes that have expired and not been respawned by init . The exit field appears for dead processes and contains the termination and exit values (as returned by wait), of the dead process. This can be useful in determining why a process terminated. -H -l Output column headings above the regular output. List only those lines on which the system is waiting for someone to login. The name field is LOGIN in such cases. Other fields are the same as for user entries except that the state field does not exist. -m -n x Output only information the current terminal. Take a numeric argument, x, which specifies the number of users to display per line. x must be at least 1. The -n option may only be used with -q. -p List any other process which is currently active and has been previously spawned by init . The name field is the name of the program executed by init as found in /sbin/inittab. The state, line , and idle fields have no meaning. The comment field shows the id field of the line from /sbin/inittab that spawned this process. -q (quick who ) display only the names and the number of users currently logged on. When this option is used, all other options are ignored. -r -s -t Indicate the current run-level of the init process. (default) List only the name, line, and time fields. Indicate the last change to the system clock (using the date utility) by root. See su and date. -T Same as the -s option, except that the state field is also written. state is one of the characters listed under the /usr/bin/who version of this option. If

Use of General Purpose Commands in Linux

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 11

Linux Manual
the -u option is used with -T, the idle time is added to the end of the previous format. -u List only those users who are currently logged in. The name is the user's login name. The line is the name of the line as found in the directory /dev. The time is the time that the user logged in. The idle column contains the number of hours and minutes since activity last occurred on that particular line. A dot (.) indicates that the terminal has seen activity in the last minute and is therefore ``current''. If more than twenty-four hours have elapsed or the line has not been used since boot time, the entry is marked old. This field is useful when trying to determine whether a person is working at the terminal or not. The pid is the process-ID of the user's shell. The comment is the comment field associated with this line as found in /sbin/inittab. This can contain information where the terminal is located, the telephone number of the dataset, terminal if hard-wired, and so forth. am i In the "C" locale, limit the output to describing the invoking user, equivalent to the -m option. The am and i or I must be separate arguments. file Specify a path name of a file to substitute for the database of logged-on users that who uses by default. Output: [root @sample root]# who Root :0 May 18 10:36

[root @sample root]# who r Run level 5 May 18 10:36 cal Calendar for the month and the year. Syntax cal [-smjy13] [month] [year] Options: -1 -3 -s -m -j -y month Display single month output. (This is the default.) Display prev/current/next month output. Display Sunday as the first day of the week. (This is the default.) Display Monday as the first day of the week. Display Julian dates (days one-based, numbered from January 1). Display a calendar for the current year. Specifies the month for you want the calendar to be displayed. Must be the numeric representation of the month. For example: January is 1 and December is 12. year Specifies the year that you want to be displayed.
Page 12

last=S

M.S.P.V.L.Polytechnic College

Linux Manual

A single parameter specifies the year (1 - 9999) to be displayed; note the year must be fully specified: cal cannot display a calendar for 1989. Two parameters denote the month (1 - 12) and year. If no parameters are specified, the current month's calendar is displayed.

Output [root @sample root]# cal March 2012 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

[root @sample root]# cal 1992 1992

January S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

February S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

March S M Tu W Th F S 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

April S M Tu W Th F S 1 2 3 4

May S M Tu W Th F S 1 2 3 4 5 6 7 8 9

June S M Tu W Th F S 1 2 3 4 5 6

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 13

Linux Manual
July S M Tu W Th F S 1 2 3 4 2 August S M Tu W Th F S 1 3 4 5 6 7 8 September S M Tu W Th F S 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

October S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 date

November S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

December S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31

Tells you the date and time in Linux. Syntax date [-a] [-u] [-s datestr] Options: %n %t %m %d %y %D %b %e %Y %g %G %h %B %H %M %S %R %T Insert a newline. Insert a tab. Month of year (0112). Day of month (0131). Last two digits of year (0099). Date in %m/%d/%y format. Abbreviated month name. Day of month (131); pad single digits with a space. Four-digit year (e.g., 1996). Week-based year within century (0099). Solaris only. Week-based year, including the century (00009999). Solaris only. Same as %b. Full month name. Hour in 24-hour format (0023). Minute (0059). Second (0061); 61 permits leap seconds and double leap seconds. Time in %H:%M format. Time in %H:%M:%S format.
Page 14

M.S.P.V.L.Polytechnic College

Linux Manual
%k Hour (24-hour clock, 023); single digits are preceded by a space. Solaris only. %l Hour (12-hour clock, 112); single digits are preceded by a space. Solaris only. %I %p %r %a %A %w %u %U %W %V Hour in 12-hour format (0112). String to indicate a.m. or p.m. (default is AM or PM). Time in %I:%M:%S %p format. Abbreviated weekday. Full weekday. Day of week (Sunday = 0). Weekday as a decimal number (17), Sunday = 1. Solaris only. Week number in year (0053); start week on Sunday. Week number in year (0053); start week on Monday. The ISO-8601 week number (0153). In ISO-8601, weeks begin on a Monday, and week 1 of the year is the one that includes both January 4th and the first Thursday of the year. If the first Monday of January is the 2nd, 3rd, or 4th, the preceding days are part of the last week of the previous year. Solaris only. %j %Z %x %X %c Julian day of year (001366). Time-zone name. Country-specific date format. Country-specific time format. Country-specific date and time format (default is %a %b %e %T %Z %Y; e.g., Mon Feb 1 14:30:59 EST 1993). Options -a s.f - (Privileged user only.) Gradually adjust the system clock until it drifts s seconds away from what it thinks is the current time. (This allows continuous micro-adjustment of the clock while the system is running.) f is the fraction of seconds by which time drifts. By default, the clock speeds up; precede s by a -- to slow down. -u - Display or set the time using Greenwich Mean Time (UTC) .

Strings for Setting the Date A privileged user can set the date by supplying a numeric string. string consists of time, day, and year concatenated in one of three ways: time or [day]time or [day]time[year]. Note: don't type the brackets. time A two-digit hour and two-digit minute (HHMM); HH uses 24-hour format.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 15

Linux Manual
day A two-digit month and two-digit day of month (mmdd); default is current day and month. year The year specified as either the full four digits or just the last two digits; default is current year Output: [root @sample root]# date Fri May 18 15:51:12 LKT 2012 ln Creates a link to a file. Syntax lp [options] [files] ln [-f] [-n] [-s] existingfile newname Options: -f Link files without questioning the user, even if the mode of target forbids writing. This is the default if the standard input is not a terminal. -n -s Does not overwrite existing files. Makes it so that it does not create a symbolic link (not on System V.) existingfile - The file that you want to create a new link. existingfile newname directory Specifies file(s) that you want to create a link to. The new name of the file. The directory were you want the new link.

Output: [root @sample root]# ln f2 mydir [root @sample root]#cd mydir [root @sample mydir]# ls F1 lp Prints a file on System V systems. Syntax: lp -i request-ID [-c] [-m] [-p] [-s] [-w] [-d destination] [-f form-name] [-H specialhandling] [-n number] [-o options] [-p pagenumbers] [-q priority-level] [-S character-set | print-wheel] [-t title] [-T content-type [-r]] [-y mode-list] f2

M.S.P.V.L.Polytechnic College

Page 16

Linux Manual
Options: -c -m -p Makes a copy of the file that is being printed. Sends e-mail when the printing is done. Enables notification on completion of the print request. Delivery of the notification is dependent on additional software. -s -w -n number -S characterset | printwheel Suppresses the display of messages sent from lp. Displays message on screen when printing is done. The number of files to be printed. Prints the request using the character-set or print-wheel. If a form was requested and requires a character set or print wheel other than the one specified with the -S option, the request is rejected. Printers using mountable print wheels or font cartridges use the print wheel or font cartridge mounted at the time of the print request, unless the -S option is specified. Printers Using Print Wheels: If print wheel is not one listed by the LP administrator as acceptable for the printer the request is rejected unless the print wheel is already mounted on the printer. Printers Using Selectable or Programmable Character Sets: If the -S option is not specified, lp uses the standard character set. If character-set is not defined in the term info database for the printer, or is not an alias defined by the LP administrator, the request is rejected. Output: tty Print the file name of the terminal connected to standard input. Syntax tty [OPTION]... Options: -s, --silent, --quiet Output: [root @sample root]# tty /dev/pts/0 wc Short for word count, wc displays a count of lines, words, and characters in a file. Syntax: wc [-c | -m | -C ] [-l] [-w] [ file ... ] - Print nothing, only return an exit status.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 17

Linux Manual
Options: -c -m -C -l -w Count bytes. Count characters. Same as -m. Count lines. Count words delimited by white space characters or new line characters. Delimiting characters are Extended Unix Code (EUC) characters from any code set defined by iswspace() file Name of file to word count.

Output: [root @sample root]# wc b.txt 2 2 17 b.txt

[root @sample root]# ls -l| wc l 30 od od command dumps a file in octal, decimal, and other formats. Syntax: od [options] [files] od --traditional [file] [[+] offset [[+] label] ] Dump the specified files to standard output. The default is to dump in octal format, but other formats can be specified. With multiple files, concatenate them in the specified order. If no files are specified or file is -, read from standard input. With the second form, using the --traditional option, only one file can be specified.

Options: For the following options, see the later Arguments section for an explanation of the arguments bytes, size, and type. If no options are specified, the default is -A o -t d2 -w 16. -a -A - Print as named characters. Same as -ta. - radix, --address-radix=radix Specify the radix (base) for the file offsets printed at the beginning of each output line. The possible values are: d n o x -b - Decimal. - None; do not print an offset. - Octal; the default. - Hexadecimal. - Print as octal bytes. Same as -toC.
Page 18

M.S.P.V.L.Polytechnic College

Linux Manual
-c -d -f -h - Print as ASCII characters or backslash escapes. Same as -tc. - Print as unsigned decimal shorts. Same as -tu2. - Print as floating-point. Same as -tfF. - Print as hexadecimal shorts. Same as -tx2.

--help - Display a usage message and exit. -i - Print as decimal shorts. Same as -td2.

-j bytes, --skip-bytes=bytes Skip the specified number of input bytes before starting. -l - Print as decimal longs. Same as -td4.

-N bytes, --read-bytes=bytes Format and print only the specified number of input bytes. -o - Print as octal shorts. Same as -to2.

-s bytes, --strings[=bytes] Output strings that are at least bytes ASCII graphic characters long (default is 3 if bytes is not specified for --strings). Arguments bytes - Specify a number of bytes. Treated as hexadecimal if it begins with 0x or 0X, as
octal if it begins with 0, or as decimal otherwise. Append b to multiply by 512, k to multiply by 1024, or m to multiply by 10248576.

size

- Specified as part of type to indicate how many bytes to use in interpreting each
number. Types a and c do not take a size. For other types, size is a number. For type f, size can also be one of the following:

D F L

- Double. - Float. - Long double.

For the remaining types (d, o, u, x), size can be one of the following in addition to a number: C I L S type Specify the format type. The possible types are: a c - Named character. - ASCII character or backslash escape. - Character. - Integer. - Long. - Short.

dsize - Signed decimal, with size bytes per integer. fsize o u x - Floating point, with size bytes per integer. - Octal, with size bytes per integer. - Unsigned decimal, with size bytes per integer. - Hexadecimal, with size bytes per integer.
Page 19

M.S.P.V.L.Polytechnic College, Pavoorchatram

Linux Manual
Output: [root @sample root]# od d 454 [1]+Stopped [root @sample root]# od a Jhu [2]+ Stopped [root @sample root]# od -d b.txt 0000000 26726 30314 25704 26472 27235 2663 26472 od a od d

Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College

Page 20

Linux Manual Ex No: 3


Aim: To write a linux commands to implement simple filters. Commands: sort To sort the lines of the named files, use sort. Syntax sort [options] [files]

Simple Filters in Linux

Options -b -c -d -f -i - Ignore leading spaces and tabs. - Check whether files are already sorted, and if so, produce no output. - Sort in dictionary order (ignore punctuation). - Fold; ignore uppercase/lowercase differences. - Ignore nonprinting characters (those outside ASCII range 040-176). - Specify significance of input fields for sorting. See the fuller description below. Solaris only. -m -M -n -o file -r -tc -T dir -u -y[kmem] - Merge sorted input files. - Compare first three characters as months. - Sort in arithmetic (numerical) order. Put output in file. - Reverse the order of the sort. - Fields are separated with c (default is any whitespace). Use dir for temporary files. Solaris only. - Identical lines in input file appear only one (u nique) time in output. - Adjust the amount of memory (in kilobytes) sort uses. If kmem is not specified, allocate the maximum memory.

-k fieldspec

Field Specifications for -k A fieldspec has the form fieldstart[type][,fieldend[type]]. fieldstart A field number and optional starting character of the form fnum[.schar]. fnum is the field number, starting from 1. schar, if present, is the starting character within the field, also counting from 1. fieldend A field number and optional ending character of the form fnum[.echar]. fnum is the field number, starting from 1. echar, if present, is the last significant character within the field, also counting from 1.
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 21

Linux Manual
type A modifier, one of the letters b, d, f, i, M, n, or r. The effect is the same as the corresponding option, except that the b modifier only applies to the fields, not the whole line.

Output: [root @sample root]# sort -b b.txt Arul Jeya Kohila Krish [root @sample root]# sort -r b.txt Krish Kohila Jeya Arul Paste Merge corresponding lines of one or more files into vertical columns, separated by a tab.. Syntax paste [options] files

Options: Replace a filename with the standard input. -d'char' Separate columns with char instead of a tab. char can be any regular character or the following escape sequences: Note: you can separate columns with different characters by supplying more than one char. \n \t \ \0 -s Output: [root @sample root]# paste a.txt b.txt c.txt > new.txt [root @sample root]# vi new.txt Newline Tab Backslash Empty string Merge subsequent lines from one file.

M.S.P.V.L.Polytechnic College

Page 22

Linux Manual
Pr Format one or more files according to options to standard output. Each page includes a heading that consists of the page number, filename, date, and time. Syntax: pr [options] [files] Options: -a -d - Multicolumn format; list items in rows going across. - Double-spaced format.

-e[cn] - Set input tabs to every n th position (default is 8), and use c as field delimiter (default is a tab). -f -F - Separate pages using formfeed character (^L) instead of a series of blank lines. - Fold input lines (avoids truncation by -a or -m).

-hstr - Replace default header with string str. -icn - For output, replace whitespace with field delimiter c (default is a tab) every nth position (default is 8). -ln -m - Set page length to n lines (default is 66). - Merge files, printing one in each column (can't be used with -n and -a).

Text is chopped to fit. See also paste. -n[cn] - Number lines with numbers n digits in length (default is 5), followed by field separator c (default is a tab). See also nl. -on -p -r -sc -t -wn - Offset each line n spaces (default is 0). - Pause before each page. - Suppress messages for files that can't be found. - Separate columns with c (default is a tab). - Omit the page header and trailing blank lines. - Set line width to n (default is 72).

+num - Begin printing at page num (default is 1). -n -Produce output having n columns (default is 1); tabs are expanded as with -i.

Examples Print a side-by-side list, omitting heading and extra lines: $pr -m -t list.1 list.2 list.3 Alphabetize a list of states; number the lines in five columns: $sort states_50 | pr -n -5

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 23

Linux Manual
Output: root @sample root]#pr a new.txt 2012-05-19 12:18 Welcome To Mspvl Polytechnic College nl Number the lines of file in logical page segments. Numbering resets to 1 at the start of each logical page. Pages consist of a header, body, and footer; each section may be empty. Syntax nl [options] [file] Section Delimiters \:\:\: \:\: \: Start of header Start of body Start of footer Page1

Options -btype - Number lines according to type. Values are: a n t All lines. No lines. Text lines only (the default).

p"exp" Lines matching the regular expression exp only.

-dxy -ftype -htype -in -ln -nformat Ln Rn Rz -

- Use characters xy to delimit logical pages (default is \:). - Like -b, but number footer (default type is n). - Like -b, but number header (default type is n). - Increment each line number by n (default is 1). - Count n consecutive blank lines as one line. - Set line number format. Values are: Left-justify, omit leading zeros. Right-justify, omit leading zeros (default). Right-justify.

M.S.P.V.L.Polytechnic College

Page 24

Linux Manual
-p -sc -vn -wn - Do not reset numbering at start of pages. - Separate text from line number with character(s) c (default is a tab). - Number each page starting at n (default is 1). - Use n columns to show line number (default is 6).

Examples List the current directory, numbering files as 1), 2), etc.: $ls | nl -w3 -s') ' Number C source code and save it: $nl prog.c > print_prog Number only lines that begin with #include: $nl -bp"^#include" prog.c Output [root @sample root]# n1 new.txt 1 2 3 4 5 Welcome To Mspvl Polytechnic College

Cut Select a list of columns or fields from one or more files. Either -c or -f must be specified. list is a sequence of integers Syntax cut options [files] Options -b list - This list specifies byte positions, not character positions. This is important when multibyte characters are used. With this option, lines should be 1023 bytes or less in size. Solaris only. -clist - Cut the character positions identified in list. -dc - Use with -f to specify field delimiter as character c (default is tab); special characters (e.g., a space) must be quoted. -flist -n - Cut the fields identified in list. - Do not split characters. When used with -b, cut doesn't split multibyte characters. Solaris only. -s - Use with -f to suppress lines without delimiters.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 25

Linux Manual

Examples Extract usernames and real names from /etc/passwd: $cut -d: -f1,5 /etc/passwd Find out who is logged on, but list only login names: $who | cut -d" " -f1 Cut characters in the fourth column of file, and paste them back as the first column in the same file. Send the results to standard output: $cut -c4 file | paste file OUTPUT [root @sample root]# cut c2 c.txt C A head Displays the first ten lines of a file, unless otherwise stated.

Syntax head [-number | -n number] filename Options: -number -n number filename The number of the you want to display. The number of the you want to display. The file that you want to display the x amount of lines of.

Examples $head -15 myfile.txt Display the first fifteen lines of myfile.txt. Output [root @sample root]# head -3 new.txt Welcome To Mspvl tail Delivers the last part of the file. Syntax tail [+ number] [-l] [-b] [-c] [-r] [-f] [-c number | -n number]

M.S.P.V.L.Polytechnic College

Page 26

Linux Manual
Options: +number -number This option is only recognized if it is specified first. COUNT is a decimal number optionally followed by a size letter (`b', `k', `m') as in `-c', or `l' to mean count by lines, or other option letters (`cfqv'). -l -b -c -r Units of lines. Units of blocks. Units of bytes. Reverse. Copies lines from the specified starting point in the file in reverse order. The default for r is to print the entire file in reverse order. -f Follow. If the input-file is not a pipe, the program will not terminate after the line of the input-file has been copied, but will enter an endless loop, wherein it sleeps for a second and then attempts to read and copy further records from the input-file. Thus it may be used to monitor the growth of a file that is being written by some other process. -c number The number option-argument must be a decimal integer whose sign affects the location in the file, measured in bytes, to begin the copying: + none Copying starts relative to the beginning of the file. Copying starts relative to the end of the file. Copying starts relative to the end of the file.

The origin for counting is 1; that is, -c+1 represents the first byte of the file, -c-1 the last. -n number Equivalent to -c number, except the starting location in the file is measured in lines instead of bytes. The origin for counting is 1; that is, -n+1 represents the first line of the file, -n-1 the last. file Name of the file you wish to display

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 27

Linux Manual
Examples $tail myfile.txt The above example would list the last 10 (default) lines of the file myfile.txt. $tail myfile.txt -n 100 The above example would list the last 100 lines in the file myfile.txt.

$tail -f myfile.txt This next example displays the last 10 lines and then update the file as new lines are being added. This is a great command to use to watch log files or logs in real-time. $tail -f access.log | grep 24.10.160.10 Finally, if you're trying to view a file such as the Apache access log file that is updated frequently you can pipe its output through the grep command to filter out only the content you want. In this above example, we're watching the access.log for any IP address of 24.10.160.10 OUTPUT [root @sample root]# tail -2 new.txt Polytechnic College

Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College

Page 28

Linux Manual

Ex No: 4
Aim:

Advanced Filters in Linux

To write a Linux commands to implement advanced filters. Commands: egrep Search one or more files for lines that match a regular expression regexp. egrep doesn't support the metacharacters \(, \), \n, \<, \>, \{, or \}, but does support the other metacharacters, as well as the extended set +, ?, |, and ( ). Syntax egrep [options] [regexp] [files] Options -b -c -e regexp -f file -h -i -l -n -s - Precede each line with its block number. (Not terribly useful.) - Print only a count of matched lines. - Use this if regexp begins with -. - Take expression from file. - List matched lines but not filenames (inverse of -l). - Ignore uppercase and lowercase distinctions. - List filenames but not matched lines. - Print lines and their line numbers. - Silent mode: print only error messages, and return the exit status. Not on SVR4, but common on most commercial Unix systems. -v Examples Search for occurrences of Victor or Victoria in file: $egrep 'Victor(ia)?' file $egrep '(Victor|Victoria)' file Find and print strings such as old.doc1 or new.doc2 in files, and include their line numbers: $egrep -n '(old|new)\.doc?' files Output [root @sample root]# egrep spam poem.txt Mary fried a lot of spam Jill had a lamp spamwich [root @sample root]# egrep sp(am)? poem.txt Mary fried a lot of spam Jill had a lamp spamwich
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 29

- Print all lines that don't match regexp.

Linux Manual
fgrep Search one or more files for lines that match a literal, text-string pattern. Because fgrep does not support regular expressions, it is faster than grep. Syntax fgrep [options] [pattern] [files] Options -b -c - Precede each line with its block number. (Not terribly useful.) - Print only a count of matched lines.

-e pat - Use this if pat begins with . -ffile -h -i -l -n -s - Take a list of patterns from file. - Print matched lines but not filenames (inverse of -l). - Ignore uppercase and lowercase distinctions. - List filenames but not matched lines. - Print lines and their line numbers. - Silent mode: print only error messages, and return the exit status. Not on SVR4, but common on most commercial Unix systems. -v -x - Print all lines that don't match pattern. - Print lines only if pattern matches the entire line.

Examples Print lines in file that don't contain any spaces: $fgrep -v ' ' file Print lines in file that contain the words in spell_list: $fgrep -f spell_list file Output [root @sample root]# fgrep spam poem.txt Mary fried a lot of spam Jill had a lamp spamwich grep Search one or more files for lines that match a regular expression regexp.. Syntax grep [options] regexp [files] Options -b -c - Precede each line with its block number. (Not terribly useful.) - Print only a count of matched lines.

-e pat - Use this if pat begins with . Solaris: this option is only available in /usr/xpg4/bin/grep, not /usr/bin/grep. It is common, though, on many modern Unix systems.
M.S.P.V.L.Polytechnic College Page 30

Linux Manual
-h -i -l -n -s -v -w - Print matched lines but not filenames (inverse of -l). - Ignore uppercase and lowercase distinctions. - List filenames but not matched lines. - Print lines and their line numbers. - Suppress error messages for nonexistent or unreadable files. - Print all lines that don't match regexp. - Restrict regexp to matching a whole word (like using \< and \> in vi). Not on SVR4, but common on many commercial Unix systems. Examples List the number of users who use the C shell: $grep -c /bin/csh /etc/passwd List header files that have at least one #include directive: $grep -l '^#include' /usr/include/* List files that don't contain pattern: $grep -c pattern files | grep :0

Output [root @sample root]# cat> poem.txt Mary had a little lamp Mary fried a lot of spam Jack ate a Spam sandwich Jill had a lamp spamwich [root @sample root]# grep spam poem.txt Mary fried a lot of spam Jill had a lamp spamwich [root @sample root]# grep i spam poem.txt Mary fried a lot of spam Jack ate a Spam sandwich Jill had a lamp spamwich [root @sample root]# grep ic spam poem.txt 3 [root @sample root]# grep i -v spam poem.txt Mary had a little lamp [root @sample root]# grep i -v spam poem.txt

Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 31

Linux Manual

Ex No: 5
Aim:

Process Management Command in Linux

To Write a commands to know the details of process status and process management. COMMANDS: ps Reports the process status. Syntax ps [-a] [-A] [-c] [-d] [-e] [-f] [-j] [-l] [-L] [-P] [-y] [ -g grplist ] [ -n namelist ] [-o format ] [ -p proclist ] [ -s sidlist ] [ -t term] [ -u uidlist ] [ -U uidlist ] [ -G gidlist ] Options: -a List information all processes most frequently requested: all those except process group leaders and processes not associated with a terminal. -A -c List information for all processes. Identical to -e, below. Print information in a format that reflects scheduler properties as described in priocntl. The -c option affects the output of the -f and -l options, as described below. -d -e -f -j -l -L List information all processes except session leaders. List information every process now running. Generate a full listing. Print session ID and process group ID. Generate a long listing. Print information each light weight process (lwp) in each selected process. -P Print the number of the processor to which the process or lwp is bound, if any, under an additional column header, PSR. -y Under a long listing (-l), omit the obsolete F and ADDR columns and include an RSS column to report the resident set size of the process. Under the -y option, both RSS and SZ will be reported in units of kilobytes instead of pages. -g grplist List only process data whose group leader's ID number(s) appears in grplist. (A group leader is a process whose process ID number is identical to its process group ID number.) -n namelist Specify the name of an alternative system namelist file in place of the default. This option is accepted for compatibility, but is ignored.
M.S.P.V.L.Polytechnic College Page 32

Linux Manual
-o format Print information according to the format specification given in format. This is fully described in DISPLAY FORMATS. Multiple -o options can be specified; the format specification will be interpreted as the space-character-separated concatenation of all the format option-arguments. -p proclist List only process data whose process ID numbers are given in proclist. -s sidlist -t term List information on all session leaders whose IDs appear in sidlist. List only process data associated with term. Terminal identifiers are specified as a device file name, and an identifier. For example, term/a, or pts/0. -u uidlist List only process data whose effective user ID number or login name is given in uidlist. In the listing, the numerical user ID will be printed unless you give the -f option, which prints the login name. -U uidlist List information for processes whose real user ID numbers or login names are given in uidlist. The uidlist must be a single argument in the form of a blank- or comma-separated list. -G gidlist List information for processes whose real group ID numbers are given in gidlist. The gidlist must be a single argument in the form of a blankor comma-separated list. Examples $ps Typing ps alone would list the current running processes. Below is an example of the output that would be generated by the ps command. PID TTY TIME CMD 6874 pts/9 0:00 6877 pts/9 0:01 418 pts/9 0:00 $ps -ef Display full information each of the processes currently running. UID PID PPID C STIME TTY TIME CMD hope 29197 18961 0 Sep27 ? 00:00:06 sshd: hope@pts/87 hope 32097 29197 0 Sep27 pts/87 00:00:00 -csh hope 7209 32097 0 12:17 pts/87 00:00:00 ps ef ksh csh csh

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 33

Linux Manual
$ps -l Displays processes including those that are in a wait state, similar to the below example. F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD 0 T 0 12308 29722 0 80 0 - 16136 finish pts/0 00:00:00 pico 0 R 0 12530 29722 0 80 0 15884 - pts/0 00:00:00 ps 4 S 0 29722 29581 0 80 0 - 16525 wait pts/0 00:00:00 bash

Output [root @sample root]# ps PID TTY TIME CMD 00:00:00 cut 00:00:00 grep 00:00:00 ps

2066 PTS/0 2039 PTS/0 2068 PTS/0 [root @sample root]# ps ef UID root bash root bash root 2229 1 2193 PID 2163

PPID C 2019 0

STIME TTY 10:33

TIME CMD pts/1 00:00:00

2019 0

10:40

pts/1 00:00:00

10:

00:00:03

/usr/libexec/nau root ps ef . . [root @sample root]# ps aux USER Root Root PID 1 2 %CPU %MEM 0.0 0.0 0.2 0.0 VSZ RSS TTY ? ? STAT START TIME COMMAND S SW 09:10 0:04 09:10 0:00 init [keventd] 2243 2163 0 11:08 pts/1 00:00:00

1336 432 0 0

. Root 2244 0.0 0.4 2766 796 pts/1 R 11:08 0:00 ps aux

[root @sample root]# ps ux USER Root Root PID 1 2 %CPU %MEM 0.0 0.0 0.2 0.0 VSZ RSS TTY ? ? STAT START TIME COMMAND S SW 09:10 0:04 09:10 0:00 init [keventd]

1336 432 0 0

. Root 2245 0.0 0.4 2624 708 pts/1 R 11:09 0:00 ps ux


M.S.P.V.L.Polytechnic College Page 34

Linux Manual
nice Invokes a command with an altered scheduling priority. Syntax nice [-increment | -n increment ] command [argument ... ] Options: -increment | -n increment increment must be in the range 1-19; if not specified, an increment of 10 is assumed. An increment greater than 19 is equivalent to 19. The super-user may run commands with priority higher than normal by using a negative increment such as -10. A negative increment assigned by an unprivileged user is ignored. command The name of a command that is to be invoked. If command names any of the special built-in utilities, the results are undefined. argument Examples $nice +13 pico myfile.txt Runs the pico command on myfile.txt with an increment of +13. Output [root @sample root]# ps axl F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY Any string to be supplied as an argument when invoking command.

TIME CMD 100 0 2229 1 15 0 19036 8672 schedu S ?

0:04 /usr/libexe . 000 0 2292 2019 15 0 4192 1504 wait4 S pts/0

0:00 bash 000 0 2322 2292 16 0 3124 1212 R pts/0

0:00 ps -axl [root @sample root]# sudo nice n 12 bash [root @sample root]# ps axl F UID PID PPID PRI NI VSZ RSS WCHAN STAT TTY

TIME CMD 100 0 2229 1 15 0 19036 8672 schedu S ?

0:04 /usr/libexe . 000 0 2292 2019 15 0 4192 1504 wait4 S pts/0

0:00 bash 000 0 2322 2292 12 0 3124 1212 R pts/0

0:00 ps axl
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 35

Linux Manual
kill Cancels a job.

Syntax kill [-s] [-l] %pid Options: -s Specify the signal to send, using one of the symbolic names defined in the <signal.h> description. Values of signal will be recognized in a case independent fashion, without the SIG prefix. In addition, the symbolic name 0 will be recognized, representing the signal value zero. The corresponding signal will be sent instead of SIGTERM. -l Write all values of signal supported by the implementation, if no operand is given. If an exit_status operand is given and it is a value of the ? shell special parameter and wait corresponding to a process that was ter minated by a signal, the signal corresponding to the signal that terminated the process will be written. If an exit_status operand is given and it is the unsigned decimal integer value of a signal number, the signal corresponding to that signal will be written. Otherwise, the results are unspecified. pid One of the following 1. A decimal integer specifying a process or process group to be signaled. The process or processes selected by positive, negative and zero values of the pid operand will be as

described for the kill function. If process number 0 is specified, all processes in the process group are signaled. If the first pid operand is negative, it should be preceded by -- to keep it from being interpreted as an option. 2. A job control job ID that identifies a background process group to be signaled. The job control job ID notation is applicable only for invocations of kill in the current shell execution environment. Note the job control job ID pid is available only on systems supporting the job control option. Examples $kill -s kill 100 -165 Kills job 1 of uid 165 When running the kill command you may receive the error "Operation not permitted", this is often encountered when you're killing the wrong group id

M.S.P.V.L.Polytechnic College

Page 36

Linux Manual
(often 1,2,3 or low number jobs) that you don't have permission to kill. If you wish to see the group id of the background task run jobs l\

Output [root @sample root]# kill -9 2 [root @sample root]# ps ux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME

COMMAND Root 1 init Root 3 0.0 0.0 0 0 ? SW 09:10 0:00 0.0 0.2 1336 432 ? S 09:10 0:04

[kapmd] . Root ux [1] KILLED mail (wd: ~) 2245 0.0 0.4 2624 708 pts/1 R 11:09 0:00 ps

nohup Runs a command even if the session is disconnected or the user logs out. Syntax nohup command [argument...] nohup -p [-Fa] pid [pid...] nohup -g [-Fa] gpid [gpid...] nohup command [argument...] Options: -a Always changes the signal disposition of target processes. This option is valid only when specified with -p or -g. -F Force. Grabs the target processes even if another process has control. This option is valid only when specified with -p or -g. -g Operates on a list of process groups. This option is not valid with -p. -p pid gpid --help --version Operates on a list of processes. This option is not valid with -g. A decimal process ID to be manipulated by nohup -p. A decimal process group ID to be manipulated by nohup Displays help screen. Output version information and exit.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 37

Linux Manual
Examples $nohup find -name '*' -size +1000k > log.txt In the above example the above find command would be ran using nohup and continue to perform a find for any file bigger then 1000k regardless of connectivity logging everything found to the log.txt file.

Output [root @sample root]# nohup ls & [1] 2354 [root @sample root]# nohup: appending output to nohup.out Exit [root @sample root]# tail nohup.out John Linux Mspvl Mydir Newproject Nohup.out [root @sample root]# tail f nohup.out John Linux Mspvl Mydir Newproject Nohup.out Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College

Page 38

Linux Manual

Ex No: 6
Aim:

Communication Commands in Linux

To write a communication commands to understand their usage. COMMANDS Write This is a utility for terminal-to-terminal communication. It allows sending lines from your terminal (console or xterm) to that of another user. The mesg command may, of course, be used to disable write access to a terminal NAME write - send a message to another user Syntax write user [ttyname] Output [root @sample root]# who User1 pts/0 2007-03-10 02:21 (:0.0)

[root @sample root]# write User1 pts/0 Hi Good morning

Mail mail - send and receive mail The mail command allows you to read or send mail. If users is left blank, it allows you to read mail. If users has a value, then it allows you send mail to those users. Syntax mail [options] [users] Options for reading mail: -e Check if mail exists. Exit status is 0 if mail exists and 1 if mail does not exist. -f file -F names -h -i -p Read mail from mailbox called file. Forward mail to names. Displays messages in a window. Ignore interrupts Displays all messages.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 39

Linux Manual
-P -q -r -U -v Displays all messages with header lines. Terminate when an interrupt occurs. Displays oldest messages first. Convert uucp-type addresses to Internet format. Verbose.

Options for sending mail: -m type Display a "Message-type:" line at the heading of the message, followed by type. -t Display a "To:" line at the heading of the message with the names of the recipients. -w Send mail to users without waiting for a remote transfer program to finish. -F -h n Save message in a file called the name of the first recipient. If message has not been sent after n network connections, do not send message. -i -r address -s subject -U -v Output: [root@sample root]$ mail Subject: MTA Microsoft Technology Associate exam is conducted for both 2 and 3 year students. News: Description : Displays message to all the users. Syntax: $ news [options] [news item] Option: -a -s -c - displays all of the news items - displays the names of all of the news items. - displays a count of all of the news items Ignore interrupts address is the return address for mail messages. Displays subject in the subject header. Convert uucp-type addresses to Internet format. Verbose.

M.S.P.V.L.Polytechnic College

Page 40

Linux Manual
Output: [root@sample root]$ cat / user /news/winner MCA guys are winners in s/w contest at GRD Granddays at 8pm [su@localhost su]$ news winner (root) wed dec 10 12:53:50 MCA guys are winners in s/w contest at GRD Granddays at 8pm. wall wall -- To broadcast a message to all users connected to the server. The length of the message is limited to 20 lines Syntax wall [ message ] Press Ctrl+d Output: [root@sample root]$wall Do Your Work Perfectly. [root@sample root]$ Broadcast message from root(pts/0)(Mon Apr 21 15:01:22 2008): Do Your Work Perfectly. calendar Displays appointments and reminders for the date. Syntax Calendar Examples $calendar Display appointments if any.

Result: Thus the above Communication Commands were executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 41

Linux Manual

Ex No: 7
Aim:

Pattern Device Pattern using Meta Character in Linux

To write a Linux commands to perform device pattern using meta character to match each of the following situation. Commands: a) ALL TWO CHARACTER FILENAMES. Syntax: $ ls ?? Output: [root@sample root]$ ls ?? F1 f2 f6 f9

b) ALL FILENAMES CONSISTING OF TWO LOWERCASE LETTERS. Syntax: $ls *[a-z]?? Output: [root@sample root]$ ls *[a-z]?? 1 Greet1 linux: mydir: f1 f2 anaconda-ks.cfg f9 doc f1 C3 f2 c5 f3 c6 addn copy jey purple

newproject: f4

C)ALL FILENAMES ENDING WITH C. Syntax: $ ls *c Output: [root@sample root]$ ls *c doc

M.S.P.V.L.Polytechnic College

Page 42

Linux Manual
D)ALL FILENAMES BEGINNING WITH C AND ENDING WITH DIGIT Syntax: $ ls c*[0-9] Output: [root@sample root]$ ls c*[0-9] C3 c5 c6

E)ALL FILENAMES BEGINNING WITH P AND HAVING AT SOMEWHERE Syntax: $ls p*?p* Output: [root@sample root]$ ls p*?p* purple

Result: Thus the above commands were executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 43

Linux Manual

SHELL SCRIPTS PROGRAMS


Ex No: 8
Aim: To write a Shell script program that accepts a numerical value N & display the decremented value of N till it reaches 0. Procedure: 1. Create a new vi editor file. 2. Get the integer value of n. 3. Check the n value greater than zero then print the n value. 4. Decrement the variable n. 5. Repeat the steps up to this condition false.(i.e. n>0) 6. Print the result. Program #!bin/bash echo ENTER THE INTEGER VALUE: read n while [ $n ge 0 ] do echo $n let n done Output [root@sample raja]# bash addn ENTER THE INTEGER VALUE: 6 6 5 4 3 2 1 0 Result: Thus the Shell script program to display the decremented integer value was executed successfully.

Display the decremented value of N.

M.S.P.V.L.Polytechnic College

Page 44

Linux Manual Ex No: 9


Aim: To Write a Shell script program that takes three command line arguments. The first argument is the name of the destination file and the other two arguments are names of files to be placed in the destination file. Procedure: 1. Create a new vi editor file. 2. Get the name of the destination file, 1st source file and 2nd source file. 3. Concatenate the two files and copied into the destination file. 4. Check the file status with 0. 5. If it is equal then print File Copied Successfully otherwise print Problem copying file. Program #!/bin/bash echo Enter the name of the destination file : read dest echo Enter the name of the 1st source file : read src1 echo Enter the name of the 2nd source file : read src2 cat $src1 $src2 > $dest status=$? If [ $status eq 0 ] Then echo File Copied Successfully Else echo Problem copying file fi Output [root@sample jeya]# bash copy Enter the name of the destination file : F1 Enter the name of the 1st source file: F2 Enter the name of the 2nd source file: F3 File copied successfully. Result: Thus the program to move the two files into another file using command line arguments was executed successfully.
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 45

Performing File Moment Using Command Line Arguments

Linux Manual

Ex No: 10
Aim:

Printing the file Content

To write a Shell script program to print the content of the file from the given line number to the next given line number. Procedure: 1. Create a new vi editor file. 2. $# -eq 0, then print the Error msg. 3. If $# -eq 3, a. If $# -eq 3, then print the content from the given line number. b. Else print the Error opening file 4. Else print the missing arguments.

Program #!/bin/bash if [ $# -eq 0 ] then echo "$0:Error command arguments missing!" echo "Usage: $0 start_line uptoline filename" echo "Where start_line is line number from which you would like to print file" echo "uptoline is line number upto which would like to print" echo "For eg. $0 5 5 myfile" echo "Here from myfile total 5 lines printed starting from line no. 5 to" echo "line no 10." exit 1 fi if [ $# -eq 3 ]; then if [ -e $3 ]; then tail +$1 $3 | head -n$2 else echo "$0: Error opening file $3" exit 2 fi else echo "Missing arguments!" fi

M.S.P.V.L.Polytechnic College

Page 46

Linux Manual

Output [root@sample jeya]# bash print file 5 5 copy read src1 echo Enter the name of the 2nd source file : read src2 cat $src1 $src2 > $dest status=$?

Result: Thus the Shell script program to print the content of the file from the given line number to the next given line number was executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 47

Linux Manual

Ex No: 11a

Display the Message in Login Session

Aim: To write a Shell script program to say Good morning/Afternoon/Evening as u log into system. Procedure: 1. Create a new vi editor file. 2. Set the value of hour. 3. Compare the hour with time of zero, 12and 18. 4. If it is greater than 0 and less than 12 print the string is GOOD MORNING then if it is greater than 12 and less than 18 print the string is GOOD AFTERNOON otherwise print the string is GOOD EVENING. Program #!/bin/bash Hour=$(date + %H) If [ $hour ge 0 a $hour lt 12 ] Then Greet=GOOD MORNING,$USER elif [ $hour ge 12 a $hour lt 18 ] Then Greet=GOOD AFTERNOON,$USER Else Greet=GOOD EVENING,$USER Fi Echo $greet Output [root@sample raja]# bash greeting GOOD AFTERNOON, root

Result: Thus the Shell script program to say Good morning/Afternoon/Evening as u log into system was executed successfully.

M.S.P.V.L.Polytechnic College

Page 48

Linux Manual

Ex No: 11b
Aim:

Dec To Print the date in a Decided Format

To write a Shell script program to print the date information. Procedure: 1. Create a new vi editor file. 2. Enter the command is date. 3. Print the today date information. Program #!/bin/bash TODAY=$(date + %X %a %d %b %Y) Echo ------------------------------------------------ Echo Today Date : $TODAY ECHO ----------------------------------------------- Output [root@sample jeya]# bash date ----------------------------------------------------------Today Date : 03: 52 :33 PM Thu 17 May 2012 -----------------------------------------------------------

Result: Thus the Shell script program to print the date information was executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 49

Linux Manual

Ex No: 12
Aim:

Shell script that tells you its name and PID you

To Write a Shell script program that tells u its name and PID. Procedure: 1. Create a new vi editor file. 2. Enter the command is Ps u into file. 3. Print the name and PID information. Program #!/bin/bash Ps u

Output [root@sample jeya]# bash p1 USER PID %CPU %MEM VSZ RSS TTY STAT START

TIME COMMAND Root 850 bash 0.0 0.9 4300 1664 pts/0 s 11.13 0:02

Result: Thus the Shell script program was executed successfully.

M.S.P.V.L.Polytechnic College

Page 50

Linux Manual

Ex No: 13
Aim:

Basic Calculator Using Switch Case

To develop a Basic Math calculator Using case Statement. Procedure: 1) Create a new file. 2) Read the operands. 3) Select any one operation from the list. 4) Perform the operation. 5) Print the result. Program: # Implementation of Calculator application #!bin/bash j=1 while [ $j -eq 1 ] do echo "Enter the First Operand;" read f1 echo "Enter the second operand:" read f2 echo "1-> Addition" echo "2-> Subtraction" echo "3-> Multiplication" echo "4-> Division" echo "Enter your choice" read n case "$n" in 1) echo "Addition" f3=$((f1+f2)) echo "The result is:$f3" ;; 2) echo "Subtraction" let "f4=$f1 - $f2" echo "The result is:$f4" ;; 3)
M.S.P.V.L.Polytechnic College, Pavoorchatram Page 51

Linux Manual
echo "Multiplication" let "f5=$f1 * $f2" echo "The result is:$f5" ;; 4) echo "Division" let "f6=$f1 / $f2" echo "The result is:$f6" ;; esac echo "Do you want to continue(press:1 otherwise press any key to quit)" read j done Output: [su@localhost su]$ bash u Enter the First Operand; 23 Enter the second operand: 23 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 1 Addition The result is:46 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 20 Enter the second operand: 2 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 2
M.S.P.V.L.Polytechnic College Page 52

Linux Manual
Subtraction The result is:18 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 24 Enter the second operand: 2 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 3 Multiplication The result is:48 Do you want to continue(press:1 otherwise press any key to quit) 1 Enter the First Operand; 24 Enter the second operand: 12 1-> Addition 2-> Subtraction 3-> Multiplication 4-> Division Enter your choice 4 Division The result is:2 Do you want to continue(press:1 otherwise press any key to quit) q [su@localhost su]$

Result: Thus the above program to develop a calculator application was executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 53

Linux Manual

Ex No: 14
Aim:

Sent the Greeting to user

To Write a Shell script program that that takes a login name as a command line argument & reports when that person logs in. Send greeting to that person. Procedure: 1. Create a new vi editor file. 2. Enter the command in to file. 3. Print the logged on to the system information. Program #!/bin/bash Echo The user $argv[1] is logged on to the system on Who | grep $argv[1] | cut c22-38

Output [root@sample jeya]# bash e2 The user [1] is logged on to the system on May 17 11:12

Result: Thus the Shell script program to that that takes a login name as command line argument & reports when that person logs in. Send greeting to that person was executed successfully.

M.S.P.V.L.Polytechnic College

Page 54

Linux Manual

Ex No: 15
Aim:

Report

To write a Shell script program that takes a command line argument and reports on whether its a file or directory or something. Procedure: 1. Create a new vi editor file. 2. Get the name of the file or directory. 3. Compare the name of the file or directory. 4. If it is file name print the string is file then if it is directory name print the string is Directory otherwise print the string is Not. Program #!/bin/bash echo "Enter a file name:" read f if [ -f $f ] then echo "File" elif [ -d $f ] then echo "Directory" else echo "Not" fi

Output [root@sample jeya]# bash report

Enter a file name: F1 File Result: Thus the Shell script program to takes a command line argument & reports on whether its a file or directory or something was executed successfully.

M.S.P.V.L.Polytechnic College, Pavoorchatram

Page 55

Das könnte Ihnen auch gefallen