Subject Name: Programming Skills-V (OS)

Subject Code: 630007

1. Check the output of the following commands.

Date Command:

date (Displaying date and time) :

  • UNIX has a date command that shows the date and time in the form used on the Internet.
  • Date is a valid command, and it displays both the date and time.
  • Notice another security feature of UNIX; the command doesn’t prompt you to change either the date or time.
  • This facility is available only to the administrator, and the strange thing is that he uses the same command.

Syntax:

$date

FriAug1913:28:34IST2005

$_

$date--System Date & Time

$date + %m--Current Month (05)

$date + %d--Current day (25)

$date + %y--Current year (1986)

$date + %D--Date in format mm/dd/yy

$date + %T--Time in format HH:MM:SS

$date + %H--Hour

$date + %M--Minute

$date + %S--Second

$date + “%H%M%S”--Hour Minute Second

$echo “Today date is: `date` “-- Today date is: 25-05-1986

List directory command (ls):

To list the name file and subdirectories of the current directory ls command is use.

The order of display would be (numbers, uppercase and lowercase) – ASCII collating sequence

The command ls can be use along with a no. Of options.

Options are the predetermine arguments use along with –(hyphen)

The different options force the command to work differently

There should be one space between the command name and option

There should not be any white space between the – and option character

Options

-x : it will give multicolumn list of directory and file

-r: List in to reverse order

-t: List in time order

-a: List all hidden files including. & ..

-A: List all hidden files excluding. & ..

-i: List all the files and directories with anode(Identification Number) number

-c: List files and directories of which inode number are changed

-R: It will give recursive list of file and directories

-l: it will give the long list of file i.e.  owner, size, date and time

-F: it will list the directory with \ , Exefile with * , Symbolic link with @

Who command:

who who Lists who is logged on your machine

Options

-a : --allsame as -b -d --login -p -r -t -T –u

-b: --boottime of last system boot

-H: --headingprint line of column headings

-l: --loginprint system login processes

-m: only hostname and user associated with stdin

-p: --processprint active processes spawned by init

-q, --countall login names and number of users logged on

-s: --shortprint only name, line, and time (default)

-t–timeprint last system clock change

-u: --userslist users logged in

Calendar Command:

  • cal is a handy tools that you can invoke any time to see the calendar of any specific moth, or a complete year.
  • To see the calendar for the month of July 2009, provide the month number and year as the two argument to cal:

Syntax

$cal [Month Number Year]

Month Number Year

This option will show you the calendar for the particular month of particular year. To see the Aug 2009 calendar then following command will be invoked.

$cal 8 2009

Above command will show you the calendar for the month of august 2009.

User can see also all year calendar for the particular year for that user has to write year number after cal command.

Example

$cal2009

Above command will show you 12month calendar for the year of 2009.

With cal, you can produce the calendar for any month or year between the year 1 and 9999. This should serve our requirements.

$cal--Display calendar of the current month

$cal 02 2010--Display calendar of Feb. 2010 (Year from 1 to 9999)

PS command:

List of all the process currently running on the system

PID ttytime cmd

ProcessIDTerminal cpu timename of processassociated with process

$ps –f -give the detail list of all the process including UID

UID (User ID)PID (Process ID) PPID (Parent PID)CPU Time (in %) CMD (Process Nm)

$ps –A or –e --It will give the list of all the system process only (i.e. cat,mkdir)

$ps –a--list all the currently running user process

$ps –u--user name

Word Count command :

Print newline, word, and byte counts for each FILE, and a total line ifmore than one FILE is specified. With no FILE, or when FILE is -, readstandard input.

Syntax

wc - print newline, word, and byte counts for each file

wc [OPTION]... [FILE]...

wc [OPTION]... --files0-from=F

Options

-c: --bytesprint the byte counts

-m: --charsprint the character counts

-l: --linesprint the newline counts

--files0-from=Fread input from the files specified by NUL-terminated names infile F

-L: --max-line-lengthprint the length of the longest line

-w: --wordsprint the word counts

Cat Command:

$cat > myfile-- Create the file named myfile

Tis is my thousand file in unixt

File name is unix

Last sentences is nothing

Ctrl + d --Save the file and return to the command prompt

$cat myfile--To view the content of file myfile

$cat myfile > testfile--Copy myfile content to the testfile

$cat myfile > testfile--Append myfile content to the testfile

File naming convention

  • Name up to 255 character long
  • May or may not have an extension
  • It can contain alphabets, digits, dot (.), underscore (_), hyphen (-) anywhere
  • It can contain both upper case and lower case alphabets
  • File name are case sensitive MCA <-> Mca
  • It can have as many dots embedded in the name (i.e. m.c.a.b.c.a)
  • Name should not have white space or tab

User Name Command:

$uname--linux

$uname –r--Version of OS

$Uname –s--Name of Kernel

$uname –n--Host Name

Options

-a: print all information, in the following order, except omit –p and -i if unknown:

(Linux bic02 2.6.27-7-generic #1 SMP Fri Oct 24 06:42:44 UTC 2008 i686 GNU/Linux)

-s: --kernel-nameprint the kernel name

(Linux)

-n: --nodenameprint the network node hostname

(bic02)

-r: --kernel-releaseprint the kernel release

(2.6.27-7-generic)

-v: --kernel-versionprint the kernel version

(#1 SMP Fri Oct 24 06:42:44 UTC 2008)

-m: --machineprint the machine hardware name

(i686)

-p: --processorprint the processor type or "unknown"

(Unknown)

-i: --hardware-platformprint the hardware platform or "unknown"

(Unknown)

-o: --operating-systemprint the operating system

(GNU/Linux)

Path Command:

$pwd--Print Working Directory [absolute path]

It will display the current working directory of a user.

Make Directory:

To create a new directory this command will use.

$mkdir book

$mkdir book/ch1 book/ch2 book/ch3

$mkdir sem5/AI sem5/JAVA sem5

Remove Directory

$rmdir book--Remove the directory book

--ignore-fail-on-non-empty

ignore each failure that is exclusively because a directory is non-empty

Change Directory

$cd ..-- Move to the parent directory

$cd sem5--Move to the Directory sem5

Copy command

  • In the first command form, copy file1 to file2. If file2 exists and you have appropriate privileges, it willbe overwritten without warning (unless you use the -i option).
  • Both file1 and file2 can be any validfilename, either fully qualified or in the local directory.
  • In the second command form, copy one ormore files to directory.
  • Note that the presence of multiple files implies that you wish to copy files to adirectory. If directory doesn't exist, an error message will be printed.
  • This command form can get youintrouble if you attempt to copy a single file into a directory that doesn't exist, as the command will be interpreted as the first form and you'll end up with file2 instead of directory.

Syntax

cp [options] file1 file2

cp [options] files directory

Options

-f: Force an overwrite of existing files in the destination.

-I:Prompt interactively before overwriting destination files. It is common practice (andadvised) to alias the cp command to cp -i to prevent accidental overwrites. You mayfind that this is already done for you for user root on your Linux system.

-p:Preserve all information, including owner, group, permissions, and timestamps.Without this option, the copied file or files will have the present date and time,default permissions, owner, and group.

-r,-R:Recursively copy directories. You may use either upper- or lowercase for this option.If file1 is actually a directory instead of a file and the recursive option isspecified, file2 will be a copy of the entire hierarchy under directory file1.

-v: Display the name of each file verbosely before copying.

Example 1

Copy the messages file to the local directory (specified by .):

$ cp /var/log/messages .

Example 2

Make an identical copy, including preservation of file attributes, of directory src in new

directory src2:

$ cp -Rp src src2

Copy file1, file2, file5, file6, and file7 from the local directory into your home directory

(under bash):

$ cp file1 file2 file[567] ~

Remove command

  • Delete one or more files from the file system.
  • To remove a file, you must have write permission in thedirectory that contains the file, but you do not need write permission on the file itself.
  • The rmcommand also removes directories when the -d, -r, or –R option is used.

Syntax

rm [options] files

Options

-d:Remove directories even if they are not empty. This option is reserved forprivileged users.

-f:Force removal of write-protected files without prompting.

-I:Query interactively before removing files.

-r, -R:If the file is a directory, recursively remove the entire directory and all of itscontents, including subdirectories.

-i: removes in interactive mode

rm *To remove all files in current directory

Move Command

  • moves files and directories around in the file system.
  • This command can also be used to rename the fileMove or rename files and directories.
  • For targets on the same filesystem (partition), moving a filedoesn't relocate the contents of the file itself. Rather, the directory entry for the target is updatedwith the new location. For targets on different filesystems, such a change can't be made, so files arecopied to the target location and the original sources are deleted.
  • Note that mv is used to rename files and directories, because a rename operation requires the samedirectory entry update as a move.
  • If a target file or directory does not exist, source is renamed to target.
  • If a target file already exists, itis overwritten with source. If target is an existing directory, source is moved into that directory.
  • Ifsource is one or more files and target is a directory, the files are moved into the directory.

Syntax

mv [options] source target

mv file1 file2renames file1 with the name file2

mv file1moves file1 to its parent directory

mv file2 dir1moves file2 into subdirectory dir1

Options

-f:Force the move even if target exists, suppressing warning messages.

-I:Query interactively before moving files.

Difference Command

Reports the differences between file1 and file2. Prints file1 text flagged (<) and file2(>).

Displays line-by-line differences between pairs of text files.

Syntax

diff file1 file2

Options

-b: ignore blank spaces.

-e: produce a script of commands to recreate file2 from file1, using ed editor.

-D: merge file1 and file2 into a single file containing conditional C preprocessors (#ifdef).

Definingsymbol and then compiling yelds file2. Not defining symbol, yields file1.

-i: --ignore-caseIgnore case differences in file contents.

--ignore-file-name-caseIgnore case when comparing file names.

--no: -ignore-file-name-caseConsider case when comparing file names.

-w: --ignore-all-spaceIgnore all white space.

-B: --ignore-blank-linesIgnore changes whose lines are all blank.

-a: --textTreat all files as text.

--label: LABELUse LABEL instead of file name.

-q: --briefOutput only whether files differ.

-y: --side-by-sideOutput in two columns.

--left-columnOutput only the left column of common lines.

--suppress-common-linesDo not output common lines.

-r: --recursiveRecursively compare any subdirectories found.

-N: --new-fileTreat absent files as empty.

Change Permission Mode Command

  • Change the access mode of one or more files.
  • Only the owner or privileged user may change its mode.
  • Create mode by concatenating who, opcode and permission.

Syntax

chmod [options]mode files

Options

Following are the symbolic representation of three different roles:

  • u is for user,
  • g is for group,
  • and o is for others.

Following are the symbolic representation of three different permissions:

  • r is for read permission,
  • w is for write permission,
  • x is for execute permission.

Following are few examples on how to use the symbolic representation on chmod.

  1. Add single permission to a file/directoryChanging permission to a single set.
  • + symbol means adding permission.
  • For example, do the following to give execute permission for the user irrespective of anything else:
  • $ chmod u+x filename

2. Add multiple permission to a file/directory

Use comma to separate the multiple permission sets as shown below.

$ chmod u+r,g+x filename

3. Remove permission from a file/directory

Following example removes read and write permission for the user.

$ chmod u-rx filename

4. Change permission for all roles on a file/directory

Following example assigns execute privilege to user, group and others

(basically anybody can execute this file).

$ chmod a+x filename

5. Change execute permission only on the directories (files are not affected)

On a particular directory if you have multiple sub-directories and files,

the following command will assign execute permission only to all the sub-directories in the current directory (not the files in the current directory).

$ chmod u+X *

octal permission bits with chmod

  • Unix file and directory permission is in the form of a 3×3 structure.
  • Three permissions (read, write and execute) available for three types of users (owner, groups and others).

In the output of ls -l command, the 9 characters from 2nd to 10th position represents the permissions for the 3 types of users.

-rw-r--r-- 1 admin administrator 67 2010-10-28 09:33 alpha.sh

In the above example:

  • User (admin) has read and write permission
  • Group has read permission
  • Others have read permission

Three type of permissions:

  • read: permitted to read the contents of directory ( view files and sub-directories in that directory ).
  • write: permitted to write in to the directory. ( create files and sub-directories in that directory )
  • execute: permitted to enter into that directory.

Numeric values for the read, write and execute permissions:

  • Read 4
  • Write 2
  • Execute 1

To have combination of permissions, add required numbers.

For example, for read and write permission, it is 4+2 = 6.

Change File and Directory Permissions Using Chmod Command

You can use either the octal representation or symbolic representation to change the permission of a file or directory.

Octal representation for permissions:

  • First number is for user
  • Second number is for group
  • Third number is for others

For example, give read, write ( 4+2 = 6 ) to user and read ( 4 ) to group and others.

$ chmod 644 filename

For example, give read, execute ( 4 + 1 = 5 ) to user and read (4 ) to group, and nothing ( 0 ) to others.

$ chmod 540 filename

For example, give read, write ( 4 + 2 = 6 ) to user and nothing ( 0 ) to group, and read ( 4 ) to others.

$ chmod 604 filename

Default file permission: 644

Default directory permission: 755

Example

chmod u+x file (add permission to the user to execute the file)

chmod 751 file (chmod u=rwx, g=rx, o=x file) They are the same command.

Regular Expression

Regular expression as used in vi, grep, etc. Regular expressions are formed from single characters, concatenation of regular expressions, choice between two regular expressions, and zero or more occurrences of a regular expression.

In UNIX, regular expressions are defined using the following Meta symbols and extensions to the regular expression notation.

.Match any single character.

[xyz]Match any character enclosed in the brackets.

[A-B] Match any character in the range.

[^xyz]Complement: match any character not enclosed in the brackets.

re*The Kleene star: match zero or more occurrences of the Re.

^reRE match must occur at the beginning of a line.

re$RE match must occur at the end of line.

\\Represent the backslash

grep command

The grep command is used to read from the specified file on the command line.

Syntex

$grep [option] RE [file(s)]

option

-bDisplay, at the beginning of the output line, the number of the block in which the regular expression was found. This can be helpful in locating block numbers by context. (The first block is block zero)

-cPrint the number of lines that contain the pattern, that is, the number of matching lines.

-hPrevent the name of the file that contains the matching line from being displayed at the beginning of that line.

Note:- When searching multiple files, grep normally reports not only the matching line but also the name of the file that contains it.

-iIgnre distinctions between uppercase and lowercase during comparisons.

-lPrint one time the name of each file that contains lines that match the pattern-regardless of the actual number of matching lines in each file-on separate lines of the screen.

-nPrecede each matching line by its line number in the file.

-sSuppress error messages about nonexistent or unreadable files.

-vPrint all lines except those that contain the pattern. This reverses the logic of the search.

Examples:

1. $grep –i ‘you’ pax corn

Here the pax and corn are file name from where you want to find ‘you’ or ‘YOU’ because option i is indicating that ignoring case.

2. grep –c ‘you’ pax corn

Here you want to see that ‘you’ how many times repeated in the files. The output of above command will be this.

Output

pax : 1

corn: 5

3. grep –h ‘you’ pax corn

Above command will shows the output for the matching lines without specifying the files from which they came.

4. grep –iv ‘you’ pax corn

Above command specifies output of “every line in pax and corn that does not have ‘you’ or ‘YOU’.

5. grep ‘^The’ pax cron

The above command finds lines that begin with The.

6. $grep ‘n$’ pax corn

Above command finds lines that end with n.

sed command:

  • sed is a stream editor.
  • A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline).
  • While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient.
  • But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors.
  • sed is a multipurpose tool which combines the work of several filters.
  • It is derived from ed.
  • The sed performs non interactive operations on a data stream hence its name.
  • It uses very few options but has a host of feature that allow you to select lines and run instructions on them.
  • Learning sed will prepare you well for perl which uses many of these feature.
  • sed uses instructions to act n text.
  • An instructin combines an address for selecting lines, with an actions to be taken on them, as shown by the syntax:

Syntax