ult/Using_Linux_Tools.rst
changeset 122 70b86355e851
parent 121 caf2b538fa0a
equal deleted inserted replaced
121:caf2b538fa0a 122:70b86355e851
   120 Where *name_of_directory* is the name of the directory one wants to create. When typed as above (ie. normal usage), the new directory would be created within the current directory. On Unix, multiple directories can be specified, and *mkdir* will try to create all of them.
   120 Where *name_of_directory* is the name of the directory one wants to create. When typed as above (ie. normal usage), the new directory would be created within the current directory. On Unix, multiple directories can be specified, and *mkdir* will try to create all of them.
   121 
   121 
   122 
   122 
   123 
   123 
   124 
   124 
   125 Where am I now in the filesystem?
   125 Where am I now on the filesystem?
   126 --------------
   126 --------------
   127 pwd is a Linux / Unix command which prints the current working directory. If you wish to know the full path of the  directory in which you are in from the Linux console, then the pwd command will come to your rescue. pwd stands for Print Working Directory.
   127 pwd is a Linux / Unix command which prints the current working directory. If you wish to know the full path of the  directory in which you are in from the Linux console, then the pwd command will come to your rescue. pwd stands for Print Working Directory.
   128 
   128 
   129 Usage of pwd command::
   129 Usage of pwd command::
   130 
   130 
   208         General help using GNU software: <http://www.gnu.org/gethelp/>
   208         General help using GNU software: <http://www.gnu.org/gethelp/>
   209         Report mkdir translation bugs to <http://translationproject.org/team/>
   209         Report mkdir translation bugs to <http://translationproject.org/team/>
   210 
   210 
   211 
   211 
   212 
   212 
   213 Basic file handling
   213 Working with Files
   214 ===================
   214 ===================
   215 
   215 
   216 Copying Files
   216 Copying Files
   217 -------------
   217 -------------
   218 
   218 
   319 Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). (Note that, confusingly for beginners, permissions on the file itself are irrelevant. However, GNU rm asks for confirmation if a write-protected file is to be deleted, unless the -f option is used.)
   319 Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). (Note that, confusingly for beginners, permissions on the file itself are irrelevant. However, GNU rm asks for confirmation if a write-protected file is to be deleted, unless the -f option is used.)
   320 
   320 
   321 To delete a directory (with rm -r), one must delete all of its contents recursively. This requires that one must have read and write and execute permission to that directory (if it's not empty) and all non-empty subdirectories recursively (if there are any).
   321 To delete a directory (with rm -r), one must delete all of its contents recursively. This requires that one must have read and write and execute permission to that directory (if it's not empty) and all non-empty subdirectories recursively (if there are any).
   322 
   322 
   323 
   323 
   324 
   324 Is there a default organization system of files and Directories that Linux follows
   325 
   325 ==================================================================================
   326 
       
   327 Working with text
       
   328 =================
       
   329 
       
   330 How do I look into a file?
       
   331 ~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   332 
       
   333 more
       
   334 -----
       
   335 
       
   336 In computing, *more* is a command to view  contents of a text file one screen at a time 
       
   337 
       
   338 Usage
       
   339 ~~~~~
       
   340 
       
   341 The command-syntax is::
       
   342 
       
   343 	$ more [options] [file_name]
       
   344 
       
   345 Traversing the pages ::
       
   346 
       
   347 
       
   348      SPACE       Display next k lines of text.  Defaults to current screen
       
   349                  size.
       
   350 
       
   351 
       
   352      RETURN      Display next k lines of text.  Defaults to 1.  Argument
       
   353                  becomes new default.
       
   354 	       
       
   355      /pattern    Search for kth occurrence of regular expression.  Defaults to
       
   356                  1 .
       
   357 
       
   358 
       
   359 
       
   360 less
       
   361 -----
       
   362 
       
   363 *less*  is similar to *more* in the sense that it is used to view files , but has the extended capability of allowing both forward and backward navigation through the file. Unlike most Unix text editors/viewers, *less* does not need to read the entire file before starting, resulting in faster load times with large files.
       
   364 
       
   365 Usage
       
   366 ~~~~~~
       
   367 
       
   368 *less* can be invoked with options to change its behaviour, for example, the number of lines to display on the screen. A few options vary depending on the operating system. While *less* is displaying the file, various commands can be used to navigate through the file. These commands are based on those used by both *more* and *vi*. It is also possible to search for character patterns in the file.
       
   369 
       
   370 By default, *less* displays the contents of the file to the standard output (one screen at a time). If the file name argument is omitted, it displays the contents from standard input (usually the output of another command through a pipe). If the output is redirected to anything other than a terminal, for example a pipe to another command, less behaves like cat.
       
   371 
       
   372 The command-syntax is ::
       
   373 
       
   374 	$ less [options] file_name
       
   375 
       
   376 
       
   377 
       
   378 Frequently Used Commands
       
   379 ~~~~~~~~~~~~~~~~~~~~~~~~
       
   380 
       
   381     * [Arrows]/[Page Up]/[Page Down]/[Home]/[End]: Navigation.
       
   382 
       
   383     * [Space bar]: Next page.
       
   384 
       
   385     * b: Previous page.
       
   386 
       
   387     * ng: Jump to line number n. Default is the start of the file.
       
   388 
       
   389     * nG: Jump to line number n. Default is the end of the file.
       
   390 
       
   391     * /pattern: Search for pattern. Regular expressions can be used.
       
   392 
       
   393     * '^ or g: Go to start of file.
       
   394 
       
   395     * '$ or G: Go to end of file.
       
   396 
       
   397     * =: File information.
       
   398 
       
   399     * h: Help.
       
   400 
       
   401     * q: Quit.
       
   402 
       
   403 
       
   404 cat
       
   405 ---
       
   406 
       
   407 The *cat* command is a standard Unix program used to concatenate and display files. The name is from "catenate", a synonym of *concatenate*.
       
   408 
       
   409 The Single Unix Specification specifies the behavior that the contents of each of the files given in sequence as arguments will be written to the standard output in the same sequence, and mandates one option, -u, where each byte is printed as it is read.
       
   410 
       
   411 If the filename is specified as -, then *cat* will read from standard input at that point in the sequence. If no files are specified, *cat* will read from standard input entered.
       
   412 
       
   413 Usage ::
       
   414         $ cat foo boo
       
   415 	This is file foo
       
   416 	
       
   417 	This is file boo.
       
   418 
       
   419 Text Processing 
       
   420 ---------------
       
   421 
       
   422 
       
   423 How do look at part of a file?
       
   424 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   425 
       
   426 head
       
   427 -----
       
   428 
       
   429 *head* is a program on Unix and Unix-like systems used to display the first few lines of a text file or piped data. The command syntax is::
       
   430 
       
   431 	$ head [options] <file_name>
       
   432 
       
   433 By default, *head* will print the first 10 lines of its input to the standard output. The number of lines printed may be changed with a command line option. The following example shows the first 20 lines of filename::
       
   434 
       
   435 	$ head -n 20 filename
       
   436 
       
   437 
       
   438 
       
   439 
       
   440 tail
       
   441 ----
       
   442 
       
   443 *tail* is a program on Unix and Unix-like systems used to display the last few lines of a text file or piped data.
       
   444 
       
   445 The command-syntax is::
       
   446 
       
   447 	$ tail [options] <file_name>
       
   448 
       
   449 By default, *tail* will print the last 10 lines of its input to the standard output. With command line options the number of lines printed and the printing units (lines, blocks or bytes) may be changed. The following example shows the last 20 lines of filename::
       
   450 
       
   451 	$ tail -n 20 filename
       
   452 
       
   453 
       
   454 
       
   455 This example shows all lines of filename from the second line onwards::
       
   456 
       
   457 	$ tail -n +2 filename
       
   458 
       
   459 
       
   460 
       
   461 Monitoring a continously changing file(example: A log file) 
       
   462 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   463 
       
   464 *tail* has a special command line option *-f* (follow) that allows a file to be monitored. Instead of displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display. This is particularly useful for monitoring log files. The following command will display the last 10 lines of messages and append new lines to the display as new lines are added to messages::
       
   465 
       
   466 	$ tail -f /var/log/dmesg
       
   467 
       
   468 To interrupt tail while it is monitoring, break-in with *Ctrl+C*. This command can be run "in the background" with &, see job control.
       
   469 
       
   470 More serious Text Processing:
       
   471 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   472 
       
   473 Problem get the names of people in the following file
       
   474 -----------------------------------------------------
       
   475 ::
       
   476 
       
   477 	Foot in Mouth:Bully:Fat:Peter
       
   478 	Rich:Simple:Peabrain:Lois
       
   479 	Self-concious:Wannabe:Adolescent:Meg
       
   480 	Dim-witted:Fat:evil-monkey:Chris
       
   481 	Matricidal:Over-Ambitious:Infant:Stewy
       
   482 	Anthropomorphic:Democrat:Sensible:Brian
       
   483 
       
   484 
       
   485  	$cut -d : -f 4- file
       
   486 	
       
   487 	Peter
       
   488 	Lois
       
   489 	Meg
       
   490 	Chris
       
   491 	Stewy
       
   492 	Brian
       
   493 
       
   494 
       
   495 		
       
   496 
       
   497 
       
   498 
       
   499 cut
       
   500 ----
       
   501 
       
   502 In computing, *cut* is a Unix command line utility which is used to extract sections from each line of input — usually from a file.
       
   503 
       
   504 Extraction of line segments can typically be done by  a *delimiter (-d — the tab character by default)*. A range must be provided in which consists of one of N, N-M, N- (N to the end of the line), or -M (beginning of the line to M), where N and M are counted from 1 (there is no zeroth value). 
       
   505 
       
   506 
       
   507 Options
       
   508 -------
       
   509 ::
       
   510 
       
   511 	
       
   512 
       
   513 	
       
   514 
       
   515 
       
   516 
       
   517 paste
       
   518 ------
       
   519 
       
   520 *paste* is a Unix command line utility which is used to join files horizontally (parallel merging) by outputting lines consisting of the sequentially corresponding lines of each file specified, separated by tabs, to the standard output. It is effectively the horizontal equivalent to the utility *cat* command which operates on the vertical plane of two or more files.
       
   521 
       
   522 To paste several columns of data together into the file *www* from files *who*, *where*, and *when*::
       
   523 
       
   524 	$ paste who where when > www
       
   525 
       
   526 If the files contain:
       
   527 
       
   528 +-----------+------------+------------+
       
   529 |   who     |   where    |    when    |
       
   530 +===========+============+============+
       
   531 |  Batman   | GothamCity | January 3  |
       
   532 +-----------+------------+------------+	
       
   533 | Trillian  | Andromeda  | February 4 |
       
   534 +-----------+------------+------------+
       
   535 |  Jeeves   | London     |  March 19  |
       
   536 +-----------+------------+------------+	
       
   537 
       
   538 This creates the file named *www* containing ::
       
   539 
       
   540 	Batman            GothamCity       January 3
       
   541 	Trillian          Andromeda        February 4
       
   542 	Jeeves            London           March 19
       
   543 
       
   544 Shell Meta Characters
       
   545 ======================
       
   546 
       
   547 Unix recognizes certain special characters, called "meta characters," as command directives. The shell meta characters are recognized anywhere they appear in the command line, even if they are not surrounded by blank space. For that reason, it is safest to only use the characters A-Z, a-z, 0-9, and the period, dash, and underscore characters when naming files and directories on Unix. If your file or directory has a shell meta character in the name, you will find it difficult to use the name in a shell command.
       
   548 
       
   549 The shell meta characters include:
       
   550 
       
   551 \ / < > ! $ % ^ & * | { } [ ] " ' ` ~ ; 
       
   552 
       
   553 
       
   554 As an example,
       
   555 ::
       
   556 
       
   557 	$ ls file.*
       
   558 
       
   559 run on a directory containing the files file, file.c, file.lst, and myfile would list the files file.c and file.lst. However,::
       
   560 
       
   561 	$ ls file.?
       
   562 
       
   563 run on the same directory would only list file.c because the ? only matches one character, no more, no less. This can save you a great deal of typing time. For example, if there is a file called california_cornish_hens_with_wild_rice and no other files whose names begin with 'c', you could view the file without typing the whole name by typing this::
       
   564 
       
   565 	$ more c*
       
   566 
       
   567 because the c* matches that long file name.
       
   568 
       
   569 Filenames containing metacharacters can pose many problems and should never be intentionally created.
       
   570 
       
   571 
       
   572 Looking At Files
       
   573 ================
       
   574 
       
   575 
       
   576 
       
   577 
       
   578 more
       
   579 -----
       
   580 
       
   581 In computing, *more* is a command to view (but not modify) the contents of a text file one screen at a time (terminal pager). It is available on Unix and Unix-like systems, DOS, OS/2 and Microsoft Windows. Programs of this sort are called pagers.
       
   582 
       
   583 Usage
       
   584 ~~~~~
       
   585 
       
   586 The command-syntax is::
       
   587 
       
   588 	$ more [options] [file_name]
       
   589 
       
   590 If no file name is provided, *more* looks for input from stdin.
       
   591 
       
   592 Once *more* has obtained input, it displays as much as can fit on the current screen and waits for user input to advance, with the exception that a form feed (^L) will also cause *more* to wait at that line, regardless of the amount of text on the screen. In the lower-left corner of the screen is displayed the text "--More--" and a percentage, representing the percent of the file that *more* has paged through. (This percentage includes the text displayed on the current screen.) When *more* reaches the end of a file (100%) it exits. The most common methods of navigating through a file are *Enter*, which advances the output by one line, and *Space*, which advances the output by one screen.
       
   593 
       
   594 There are also other commands that can be used while navigating through the document; consult *more*'s *man* page for more details.
       
   595 
       
   596 
       
   597 
       
   598 less
       
   599 -----
       
   600 
       
   601 *less* is a terminal pager program on Unix, Windows and Unix-like systems used to view (but not change) the contents of a text file one screen at a time. It is similar to *more*, but has the extended capability of allowing both forward and backward navigation through the file. Unlike most Unix text editors/viewers, *less* does not need to read the entire file before starting, resulting in faster load times with large files.
       
   602 
       
   603 Usage
       
   604 ~~~~~~
       
   605 
       
   606 *less* can be invoked with options to change its behaviour, for example, the number of lines to display on the screen. A few options vary depending on the operating system. While *less* is displaying the file, various commands can be used to navigate through the file. These commands are based on those used by both *more* and *vi*. It is also possible to search for character patterns in the file.
       
   607 
       
   608 By default, *less* displays the contents of the file to the standard output (one screen at a time). If the file name argument is omitted, it displays the contents from standard input (usually the output of another command through a pipe). If the output is redirected to anything other than a terminal, for example a pipe to another command, less behaves like cat.
       
   609 
       
   610 The command-syntax is ::
       
   611 
       
   612 	$ less [options] file_name
       
   613 
       
   614 Frequently Used Options
       
   615 ~~~~~~~~~~~~~~~~~~~~~~~
       
   616 
       
   617     * -g: Highlights just the current match of any searched string.
       
   618 
       
   619     * -I: Case-insensitive searches.
       
   620 
       
   621     * -M: Shows more detailed prompt, including file position.
       
   622 
       
   623     * -N: Shows line numbers (useful for source code viewing).
       
   624 
       
   625     * -S: Disables line wrap ("chop long lines"). Long lines can be seen by side scrolling.
       
   626 
       
   627     * -?: Shows help.
       
   628 
       
   629 Frequently Used Commands
       
   630 ~~~~~~~~~~~~~~~~~~~~~~~~
       
   631 
       
   632     * [Arrows]/[Page Up]/[Page Down]/[Home]/[End]: Navigation.
       
   633 
       
   634     * [Space bar]: Next page.
       
   635 
       
   636     * b: Previous page.
       
   637 
       
   638     * ng: Jump to line number n. Default is the start of the file.
       
   639 
       
   640     * nG: Jump to line number n. Default is the end of the file.
       
   641 
       
   642     * /pattern: Search for pattern. Regular expressions can be used.
       
   643 
       
   644     * '^ or g: Go to start of file.
       
   645 
       
   646     * '$ or G: Go to end of file.
       
   647 
       
   648     * h: Help.
       
   649 
       
   650     * q: Quit.
       
   651 
       
   652 
       
   653 
       
   654 -------------------------------------------------------------------
       
   655 
       
   656 Examples 
       
   657 ~~~~~~~~~
       
   658 ::
       
   659 
       
   660 	$ less -M readme.txt                     #Read "readme.txt."
       
   661 	$ less +F /var/log/mail.log              #Follow mode for log
       
   662 	$ file * | less                          #Easier file analysis.
       
   663 	$ grep -i void *.c | less -I -p void     #Case insensitive search 		                                          for "void" in all .c files
       
   664 
       
   665 Directory Structure
       
   666 ====================
       
   667 
   326 
   668 In the File Hierarchy Standard (FHS) all files and directories appear under the root directory "/", even if they are stored on different physical devices. Note however that some of these directories may or may not be present on a Unix system depending on whether certain subsystems, such as the X Window System, are installed.
   327 In the File Hierarchy Standard (FHS) all files and directories appear under the root directory "/", even if they are stored on different physical devices. Note however that some of these directories may or may not be present on a Unix system depending on whether certain subsystems, such as the X Window System, are installed.
   669 
   328 
   670 The majority of these directories exist in all UNIX operating systems and are generally used in much the same way; however, the descriptions here are those used specifically for the FHS, and are not considered authoritative for platforms other thanmajor Linux distros.
   329 The majority of these directories exist in all UNIX operating systems and are generally used in much the same way; however, the descriptions here are those used specifically for the FHS, and are not considered authoritative for platforms other thanmajor Linux distros.
   671 
   330 
   734 
   393 
   735 This is the manual page on the UNIX filesystem. The syntax for this is::
   394 This is the manual page on the UNIX filesystem. The syntax for this is::
   736 
   395 
   737 	$ man hier
   396 	$ man hier
   738 
   397 
   739 ls -l
   398 
   740 -----
   399 
   741 
   400 
   742 Shows you huge amounts of information (permissions, owners, size, and when last modified) for folders and files. The syntax is ::
   401 
   743 
       
   744 	$ ls -l
       
   745 
       
   746 This can be done after entering the required directory. 
       
   747 
   402 
   748 Permissions and Ownership
   403 Permissions and Ownership
   749 =========================
   404 =========================
   750 
       
   751 let's check out the file permissions. File permissions are defined
       
   752 for users, groups and others. User would be the username that you are
       
   753 logging in as. Further more, users can be organized into groups for better
       
   754 administration and control. Each user will belong to at least one default
       
   755 group. Others includes anyone the above categories exclude.
       
   756 
       
   757 Given below is the result of an 'ls -l'
       
   758 
   405 
   759 drwxr-x--- 2 user group 4096 Dec 28 04:09 tmp
   406 drwxr-x--- 2 user group 4096 Dec 28 04:09 tmp
   760 -rw-r--r-- 1 user group 969 Dec 21 02:32 foo
   407 -rw-r--r-- 1 user group 969 Dec 21 02:32 foo
   761 -rwxr-xr-x 1 user group 345 Sep 1 04:12 somefile
   408 -rwxr-xr-x 1 user group 345 Sep 1 04:12 somefile
   762 
   409 
   763 Relevant information in the first column here is the file type followed by the file permissions. The third and the fourth column show the owner of the file and the group that the file belongs to.The fifth column is no bytes and sixth modification date .The first entry here is tmp. The first character in the first column is 'd', which means the tmp is a directory. The other entries here are files,as indicated by the '-'.
   410 d - The file is a directory.
   764 
   411 
   765 d rwx r-x ---
   412 r - Read permission. The file may be read. In the case of a directory, this would mean the ability to list the contents of the directory.
   766 file type users group others
   413 
   767 
   414 w - Write permission.For a directory, this defines whether you can make any changes to the contents
   768 The next 9 characters define the file permissions. These permissions are given in groups of 3 each. The first 3 characters are the permissions for the owner of the file or directory. The next 3 are permissions for the group that the file is owned by and the final 3 characters define the access permissions for everyone not part of the group. There are 3 possible attributes that make up file access permissions.
   415 of the directory. If write permission is not set then you will not be able to delete, rename or create a file.
   769 
       
   770 r - Read permission. Whether the file may be read. In the case of a directory, this would mean the ability to list the contents of the directory.
       
   771 
       
   772 w - Write permission. Whether the file may be written to or modified. For a directory, this defines whether you can make any changes to the contents
       
   773 of the directory. If write permission is not set then you will not be able
       
   774 to delete, rename or create a file.
       
   775 
   416 
   776 x - Execute permission. Whether the file may be executed. In the case of a directory, this attribute decides whether you have permission to enter,run a search through that directory or execute some program from that directory.
   417 x - Execute permission. Whether the file may be executed. In the case of a directory, this attribute decides whether you have permission to enter,run a search through that directory or execute some program from that directory.
   777 
   418 
   778 
   419 The Permission are read in the following manner::
       
   420 
       
   421     | User | Group | Others |
       
   422     |------+-------+--------|
       
   423     | drwx | rwx   | rwx    |
       
   424 
       
   425 
       
   426 Problem: Given a file with only read permission, add execute permission to User, Group and Others.
       
   427 --------------------------------------------------------------------------------------------------
       
   428 
       
   429 Solution::
       
   430 	
       
   431 	$chmod a+x executablefile
       
   432    	$ls -l executablefile
       
   433 
       
   434 Thats it .
   779 
   435 
   780 
   436 
   781 chmod
   437 chmod
   782 ------
   438 ------
   783 
   439 
   784 The *chmod* command (abbreviated from 'change mode') is a shell command and C language function in Unix and Unix-like environments. When executed, it can change file system modes of files and directories. The modes include permissions and special modes.
   440 The *chmod* command changes the  file system modes of files and directories. The modes include permissions and special modes.
   785 
   441  
   786 Usage
   442 Usage
   787 ~~~~~
   443 ~~~~~
   788 
   444 
   789 The *chmod* command options are specified like this:
   445 The *chmod* command options are specified like this:
   790 ::
   446 ::
   851 +-----+--------------+------------------------------------------------+
   507 +-----+--------------+------------------------------------------------+
   852 | w   | write        | write to a file or directory                   |   
   508 | w   | write        | write to a file or directory                   |   
   853 +-----+--------------+------------------------------------------------+
   509 +-----+--------------+------------------------------------------------+
   854 | x   | execute      | execute a file or recurse a directory tree     |
   510 | x   | execute      | execute a file or recurse a directory tree     |
   855 +-----+--------------+------------------------------------------------+
   511 +-----+--------------+------------------------------------------------+
   856 | X   | special      | which is not a permission in itself but rather |
   512 
   857 |     | execute      | can be used instead of 'x'. It applies execute |
   513 Examples
   858 |     |              | permissions to directories regardless of their |
   514 +++++++++
   859 |     |              | current permissions and applies execute        |
       
   860 |     |              | permissions to a file which already has at     |
       
   861 |     |              | least 1 execute permission bit already set     |
       
   862 |     |              | (either user, group or other). It is only      |
       
   863 |     |              | really useful when used with '+' and usually   |
       
   864 |     |              | in combination with the *-R* option for giving |
       
   865 |     |              | group or other access to a big directory tree  |
       
   866 |     |              | without setting execute permission on normal   |
       
   867 |     |              | files (such as text files), which would        |
       
   868 |     |              | normally happen if one just used 'chmod -R     |
       
   869 |     |              | a+rx .', whereas with 'X' one can do 'chmod -R |
       
   870 |     |              | a+rX .' instead.                               |
       
   871 +-----+--------------+------------------------------------------------+
       
   872 | s   | setuid/gid   | are Unix access rights flags that allow users  |
       
   873 |     |              | to run an executable with the permissions of   |
       
   874 |     |              | the executable's owner or group.They are often |
       
   875 |     |              | used to allow users on a computer system to run| 
       
   876 |     |              | programs with temporarily elevated privileges  | 
       
   877 |     |              | in order to perform a specific task. While the |
       
   878 |     |              | assumed user id or group id privileges provided|
       
   879 |     |              | are not always elevated, at a minimum they are | 
       
   880 |     |              | specific.They are needed for tasks that require|
       
   881 |     |              | higher privileges than those which a common    |
       
   882 |     |              | user has, such as changing his or her login    |  
       
   883 |     |              | password.                                      |
       
   884 +-----+--------------+------------------------------------------------+
       
   885 | t   | sticky       | The most common use of the sticky bit today is |
       
   886 |     |              | on directories, where, when set, items inside  |
       
   887 |     |              | the directory can be renamed or deleted only by|
       
   888 |     |              | the item's owner, the directory's owner, or the| 
       
   889 |     |              | superuser; without the sticky bit set, any user|
       
   890 |     |              | with write and execute permissions for the     |
       
   891 |     |              | directory can rename or delete contained files,| 
       
   892 |     |              | regardless of owner.                           |
       
   893 +-----+--------------+------------------------------------------------+
       
   894 
       
   895 The combination of these three components produces a string that is understood by the chmod command. Multiple changes can be specified by separating multiple symbolic modes with commas.
       
   896 
       
   897 Symbolic examples
       
   898 +++++++++++++++++
       
   899 
   515 
   900 Add the 'read' and 'write' permissions to the 'user' and 'group' classes of a directory:
   516 Add the 'read' and 'write' permissions to the 'user' and 'group' classes of a directory:
   901 ::
   517 ::
   902 
   518 
   903 	$ chmod ug+rw mydir
   519 	$ chmod ug+rw mydir
   909 
   525 
   910 	$ chmod a-w myfile
   526 	$ chmod a-w myfile
   911 	$ ls -l myfile
   527 	$ ls -l myfile
   912 	-r-xr-xr-x   2 starwars  yoda 96 Dec 8 12:53 myfile
   528 	-r-xr-xr-x   2 starwars  yoda 96 Dec 8 12:53 myfile
   913 
   529 
   914 Set the permissions for the *u*ser and the *g*roup to read and execute only (no write permission) on *mydir*.
       
   915 ::
       
   916 
       
   917 	$ chmod ug=rx mydir
       
   918 	$ ls -ld mydir
       
   919 	dr-xr-x---   2 starwars  yoda 96 Dec 8 12:53 mydir
       
   920 
       
   921 Octal numbers
   530 Octal numbers
   922 +++++++++++++
   531 +++++++++++++
   923 
   532 
   924 The *chmod* command also accepts three and four-digit octal numbers representing modes. Using a three-digit octal number to set the modes of a file named myfile :
   533 The *chmod* command also accepts three and four-digit octal numbers representing modes. Using a three-digit octal number to set the modes of a file named myfile :
   925 ::
   534 ::
   937 You want the user to have all the rights? : 4 + 2 + 1 = 7
   546 You want the user to have all the rights? : 4 + 2 + 1 = 7
   938 
   547 
   939 you want the group to have read and write rights : 4 + 2 = 6
   548 you want the group to have read and write rights : 4 + 2 = 6
   940 
   549 
   941 
   550 
   942 
   551 Changing Ownership of Files
   943 Since the *setuid*, *setgid* and *sticky* bits are not set, this is equivalent to:
   552 ===========================
   944 ::
       
   945 
       
   946 	$ chmod 0664 myfile
       
   947 
   553 
   948 
   554 
   949 chown
   555 chown
   950 ~~~~~
   556 ~~~~~
   951 The chown command is used to change the owner and group of files, directories and links.
   557 The chown command is used to change the owner and group of files, directories and links.
   952 
   558 
   953 By default, the owner of a filesystem object is the user that created it. The group is a set of users that share the same access permissions (i.e., read, write and execute) for that object.
   559 By default, the owner of a filesystem object is the user that created it. The group is a set of users that share the same access permissions (i.e., read, write and execute) for that object.
   954 
   560 
   955 The basic syntax for using chown to change owners is
   561 The basic syntax for using chown to change owners is::
   956 
   562 
   957     chown -v alice wonderland.txt
   563     $chown -v alice wonderland.txt
   958 
   564 
   959 
   565 -v - For verbose Mode
   960 
   566  
       
   567 alice - Username of new owner 
       
   568 
       
   569 
       
   570 
       
   571 
       
   572 
       
   573 Working with text
       
   574 =================
       
   575 
       
   576 How do I look into a file?
       
   577 ~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   578 
       
   579 more
       
   580 -----
       
   581 
       
   582 In computing, *more* is a command to view  contents of a text file one screen at a time 
       
   583 
       
   584 Usage
       
   585 ~~~~~
       
   586 
       
   587 The command-syntax is::
       
   588 
       
   589 	$ more [options] [file_name]
       
   590 
       
   591 Traversing the pages ::
       
   592 
       
   593 
       
   594      SPACE       Display next k lines of text.  Defaults to current screen
       
   595                  size.
       
   596 
       
   597 
       
   598      RETURN      Display next k lines of text.  Defaults to 1.  Argument
       
   599                  becomes new default.
       
   600 	       
       
   601      /pattern    Search for kth occurrence of regular expression.  Defaults to
       
   602                  1 .
       
   603 
       
   604 
       
   605 
       
   606 less
       
   607 -----
       
   608 
       
   609 *less*  is similar to *more* in the sense that it is used to view files , but has the extended capability of allowing both forward and backward navigation through the file. Unlike most Unix text editors/viewers, *less* does not need to read the entire file before starting, resulting in faster load times with large files.
       
   610 
       
   611 Usage
       
   612 ~~~~~~
       
   613 
       
   614 *less* can be invoked with options to change its behaviour, for example, the number of lines to display on the screen. A few options vary depending on the operating system. While *less* is displaying the file, various commands can be used to navigate through the file. These commands are based on those used by both *more* and *vi*. It is also possible to search for character patterns in the file.
       
   615 
       
   616 By default, *less* displays the contents of the file to the standard output (one screen at a time). If the file name argument is omitted, it displays the contents from standard input (usually the output of another command through a pipe). If the output is redirected to anything other than a terminal, for example a pipe to another command, less behaves like cat.
       
   617 
       
   618 The command-syntax is ::
       
   619 
       
   620 	$ less [options] file_name
       
   621 
       
   622 
       
   623 
       
   624 Frequently Used Commands
       
   625 ~~~~~~~~~~~~~~~~~~~~~~~~
       
   626 
       
   627     * [Arrows]/[Page Up]/[Page Down]/[Home]/[End]: Navigation.
       
   628 
       
   629     * [Space bar]: Next page.
       
   630 
       
   631     * b: Previous page.
       
   632 
       
   633     * ng: Jump to line number n. Default is the start of the file.
       
   634 
       
   635     * nG: Jump to line number n. Default is the end of the file.
       
   636 
       
   637     * /pattern: Search for pattern. Regular expressions can be used.
       
   638 
       
   639     * '^ or g: Go to start of file.
       
   640 
       
   641     * '$ or G: Go to end of file.
       
   642 
       
   643     * =: File information.
       
   644 
       
   645     * h: Help.
       
   646 
       
   647     * q: Quit.
       
   648 
       
   649 
       
   650 cat
       
   651 ---
       
   652 
       
   653 The *cat* command is a standard Unix program used to concatenate and display files. The name is from "catenate", a synonym of *concatenate*.
       
   654 
       
   655 The Single Unix Specification specifies the behavior that the contents of each of the files given in sequence as arguments will be written to the standard output in the same sequence, and mandates one option, -u, where each byte is printed as it is read.
       
   656 
       
   657 If the filename is specified as -, then *cat* will read from standard input at that point in the sequence. If no files are specified, *cat* will read from standard input entered.
       
   658 
       
   659 Usage ::
       
   660         $ cat foo boo
       
   661 	This is file foo
       
   662 	
       
   663 	This is file boo.
       
   664 
       
   665 Text Processing 
       
   666 ---------------
       
   667 
       
   668 
       
   669 How do look at part of a file?
       
   670 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   671 
       
   672 head
       
   673 -----
       
   674 
       
   675 *head* is a program on Unix and Unix-like systems used to display the first few lines of a text file or piped data. The command syntax is::
       
   676 
       
   677 	$ head [options] <file_name>
       
   678 
       
   679 By default, *head* will print the first 10 lines of its input to the standard output. The number of lines printed may be changed with a command line option. The following example shows the first 20 lines of somefile::
       
   680 
       
   681 	$ head -n 20 somefile
       
   682 
       
   683 
       
   684 
       
   685 
       
   686 tail
       
   687 ----
       
   688 
       
   689 *tail* is a program on Unix and Unix-like systems used to display the last few lines of a text file or piped data.
       
   690 
       
   691 The command-syntax is::
       
   692 
       
   693 	$ tail [options] <file_name>
       
   694 
       
   695 By default, *tail* will print the last 10 lines of its input to the standard output. With command line options the number of lines printed and the printing units (lines, blocks or bytes) may be changed. The following example shows the last 20 lines of somefile::
       
   696 
       
   697 	$ tail -n 20 somefile
       
   698 
       
   699 
       
   700 
       
   701 This example shows all lines of somefile from the second line onwards::
       
   702 
       
   703 	$ tail -n +2 somefile
       
   704 
       
   705 
       
   706 
       
   707 Monitoring a continously changing file(example: A log file) 
       
   708 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   709 
       
   710 *tail* has a special command line option *-f* (follow) that allows a file to be monitored. Instead of displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display. This is particularly useful for monitoring log files. The following command will display the last 10 lines of messages and append new lines to the display as new lines are added to messages::
       
   711 
       
   712 	$ tail -f /var/log/dmesg
       
   713 
       
   714 To interrupt tail while it is monitoring, break-in with *Ctrl+C*. This command can be run "in the background" with &, see job control.
       
   715 
       
   716 More serious Text Processing:
       
   717 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   718 
       
   719 Problem1. Get the names of people in the following file
       
   720 -----------------------------------------------------
       
   721 ::
       
   722 
       
   723 	Foot in Mouth:Bully:Fat:Peter
       
   724 	Rich:Simple:Peabrain:Lois
       
   725 	Self-concious:Wannabe:Adolescent:Meg
       
   726 	Dim-witted:Fat:evil-monkey:Chris
       
   727 	Matricidal:Over-Ambitious:Infant:Stewy
       
   728 	Anthropomorphic:Democrat:Sensible:Brian
       
   729 
       
   730 Soulution::
       
   731  	$cut -d : -f 4- file
       
   732 	
       
   733 	Peter
       
   734 	Lois
       
   735 	Meg
       
   736 	Chris
       
   737 	Stewy
       
   738 	Brian
       
   739 
       
   740 
       
   741 		
       
   742 
       
   743 
       
   744 
       
   745 cut
       
   746 ----
       
   747 
       
   748 In computing, *cut* is a Unix command line utility which is used to extract sections from each line of input — usually from a file.
       
   749 
       
   750 Extraction of line segments can typically be done by  a *delimiter (-d — the tab character by default)*. A range must be provided in which consists of one of N, N-M, N- (N to the end of the line), or -M (beginning of the line to M), where N and M are counted from 1 (there is no zeroth value). 
       
   751 
       
   752 
       
   753 Options
       
   754 -------
       
   755 ::
       
   756 
       
   757 	-b   select on the basis of bytes
       
   758 
       
   759         -c   select on the basis of characters
       
   760 			
       
   761 			
       
   762 	-f  select on  the basis of fields,also print any line that contains no delimiter character
       
   763 
       
   764 Problem2.Given two files of student name and marks merge them
       
   765 -------------------------------------------------------------
       
   766 
       
   767 File of students(students.txt) ::
       
   768      
       
   769      Hussain
       
   770      Dilbert
       
   771      Alex
       
   772      Raul
       
   773      Sven
       
   774 
       
   775 File of marks(marks.txt)::
       
   776      
       
   777 
       
   778      89
       
   779      98
       
   780      67
       
   781      78
       
   782      67
       
   783 
       
   784 Solution::
       
   785 
       
   786 	$paste students.txt marks.txt
       
   787 	Hussain	89
       
   788 	Dilbert	98
       
   789  	Alex	67
       
   790  	Raul	78
       
   791  	Sven	67
       
   792 
       
   793 
       
   794 	$paste -d : students.txt marks.txt
       
   795 	
       
   796 	Hussain:89
       
   797 	Dilbert:98
       
   798 	Alex:67
       
   799  	Raul:78
       
   800  	Sven:67
       
   801 
       
   802 	
       
   803 	$paste -s students.txt marks.txt
       
   804 
       
   805 	Hussain	  	 Dilbert	 Alex	 Raul	 Sven	
       
   806 	89		 98		 67	 78	 67
       
   807 
       
   808 
       
   809 
       
   810 
       
   811 paste
       
   812 ------
       
   813 
       
   814 *paste* is a Unix command line utility which is used to join files horizontally (parallel merging) by outputting lines consisting of the sequentially corresponding lines of each file specified, separated by tabs, to the standard output. 
       
   815 
       
   816 
       
   817 Some frequently used Text Processing tools
       
   818 ==========================================
       
   819 
       
   820 Given a file with names US presidents  . Sort the file  on the names . The contents of the file are mentioned below
       
   821 ::
       
   822       
       
   823        
       
   824        John%Kennedy
       
   825        Bill%Clinton
       
   826        Bill%Clinton
       
   827        Franklin%Rosevelt
       
   828        George%Bush 
       
   829        Abraham%Lincoln
       
   830        Abraham%Lincoln
       
   831        George%Washington
       
   832        George%Washington
       
   833        
       
   834 
       
   835 
       
   836 Solution:: 
       
   837 	
       
   838 	 $sort presidents.txt
       
   839 
       
   840        Abraham%Lincoln
       
   841        Abraham%Lincoln
       
   842        Bill%Clinton
       
   843        Bill%Clinton       
       
   844        Franklin%Rosevelt
       
   845        George%Bush 
       
   846        George%Washington
       
   847        George%Washington
       
   848        John%Kennedy
       
   849 
       
   850 
       
   851 Sort
       
   852 ====
       
   853 sort command with the file name as a parameter sorts the lines of the file alphabetically and prints the output on the terminal.	
       
   854 
       
   855 
       
   856 To sort the same file using the last names     
       
   857 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
       
   858 
       
   859 ::
       
   860 
       
   861 	$sort -t % -k 2 presidents.txt
       
   862 	
       
   863 	George%Bush 
       
   864         Bill%Clinton
       
   865         Bill%Clinton       
       
   866         John%Kennedy
       
   867         Abraham%Lincoln
       
   868         Abraham%Lincoln
       
   869         Franklin%Rosevelt
       
   870         George%Washington
       
   871         George%Washington
       
   872 
       
   873 
       
   874 
       
   875 	-t - specify the delimiter 
       
   876 	-k - specify the column 
       
   877 
       
   878 There are other options like -r to sort on reverse order etc ..
       
   879 
       
   880 
       
   881 
       
   882 Problem:Given a file remove all the duplicate lines in it ?
       
   883 ===========================================================
       
   884 
       
   885 File ::
       
   886      
       
   887        Abraham%Lincoln
       
   888        Abraham%Lincoln
       
   889        Bill%Clinton
       
   890        Bill%Clinton       
       
   891        Franklin%Rosevelt
       
   892        George%Bush 
       
   893        George%Washington
       
   894        George%Washington
       
   895        John%Kennedy
       
   896 
       
   897 Solution::
       
   898       
       
   899       $uniq -c sortpresidents.txt
       
   900 
       
   901 
       
   902       2 Abraham%Lincoln       
       
   903       2 Bill%Clinton
       
   904       1 Franklin%Rosevelt
       
   905       1 George%Bush 
       
   906       2 George%Washington
       
   907       1 John%Kennedy
       
   908 
       
   909 
       
   910 uniq
       
   911 ====
       
   912 
       
   913 
       
   914 ``uniq`` command removes duplicate lines next to each other.
       
   915 
       
   916 -c - also gives the no. of repetitions .
   961 
   917 
   962 
   918 
   963 Redirection and Piping
   919 Redirection and Piping
   964 =======================
   920 =======================
   965 
   921 
   966 In computing, *redirection* is a function common to most command-line interpreters, including the various Unix shells that can redirect standard streams to user-specified locations.
   922 In computing, *redirection* is a function common to most command-line interpreters, including the various Unix shells that can redirect standard streams to user-specified locations.
   967 
   923 
   968 
   924 
   969 
   925 
       
   926 Problem: Get a sorted list of all xml file in directory ?
       
   927 
       
   928 Soulition::
       
   929 	$ls | grep '.xml$' > xmllist
       
   930 
       
   931 
       
   932 This problem introduced a lot of concepts we shall look at them one by one .
       
   933 
       
   934 
   970 Redirecting standard input and standard output
   935 Redirecting standard input and standard output
   971 -----------------------------------------------
   936 -----------------------------------------------
   972 
   937 
   973 Redirection is usually implemented by placing certain characters between commands. Typically, the syntax of these characters is as follows::
   938 Redirection refers to redirecting standard Input or output to a command or file .
   974 
   939 
   975 	$ command1 > file1
   940 Ex::
   976 
   941 
   977 executes *command1*, placing the output in file1. Note that this will truncate any existing data in *file1*. To append output to the end of the file, use the >> operator.::
   942 	$ command > file1
   978 
   943 
   979 	$ command1 < file1
   944 This command executes *command1*, placing the output in file1. Note that this will truncate any existing data in *file1*. To append output to the end of the file, use the >> operator like this
       
   945      	$ command >> file1
       
   946 	
       
   947 Ex2::
       
   948 	
       
   949 
       
   950 
       
   951 	$ command < file1
   980 
   952 
   981 executes *command1*, using *file1* as the source of input (as opposed to the keyboard).::
   953 executes *command1*, using *file1* as the source of input (as opposed to the keyboard).::
   982 
   954 
   983 	$ command1 < infile > outfile
   955 	$ command1 < infile > outfile
   984 
   956 
   985 combines the two capabilities: *command1* reads from *infile* and writes to *outfile*
   957 combines the two capabilities: *command1* reads from *infile* and writes to *outfile*
       
   958 
       
   959 
       
   960 In this example we see redirection in the end ::
       
   961 
       
   962    $(some commands) > xmllist 
       
   963 
       
   964 
       
   965 
   986 
   966 
   987 Piping
   967 Piping
   988 -------
   968 -------
   989 
   969 
   990 Programs can be run together such that one program reads the output from another with no need for an explicit intermediate file:
   970 Programs can be run together such that one program reads the output from another with no need for an explicit intermediate file:
   991 A pipeline of two programs run on a text terminal::
   971 A pipeline of two programs run on a text terminal::
   992 
   972 
   993 	$ command1 | command2
   973 	$ command1 | command2
   994 
   974 
   995 executes *command1*, using its output as the input for *command2* (commonly called piping, since the "|" character is known as a "pipe").
   975 executes *command1*, using its output as the input for *command2* (commonly called piping, since the '|' character is known as a "pipe").
   996 
   976 
   997 This is equivalent to using two redirects and a temporary file::
   977 This is equivalent to using two redirects and a temporary file ::
   998 
   978 
   999 	$ command1 > tempfile
   979 	$ command1 > tempfile
  1000 	$ command2 < tempfile
   980 	$ command2 < tempfile
  1001 	$ rm tempfile
   981 	$ rm tempfile
  1002 
   982 
  1003 A good example for command piping is combining *echo* with another command to achieve something interactive in a non-interactive shell, e.g.::
   983 In the above example we used piping in the following manner ::
  1004 
   984 
  1005 	$ echo -e "user\npass" | ftp localhost
   985 	$ echo
  1006 
   986 
  1007 This runs the ftp client with input user, press return, then pass.
   987 This runs the ftp client with input user, press return, then pass.
  1008 
   988 
  1009 Redirecting to and from the standard file handles
   989 Redirecting to and from the standard file handles
  1010 --------------------------------------------------
   990 --------------------------------------------------
  1024 For example:
  1004 For example:
  1025 ::
  1005 ::
  1026 
  1006 
  1027 	$ command1 2> file1
  1007 	$ command1 2> file1
  1028 
  1008 
  1029 executes *command1*, directing the standard error stream to *file1*.
  1009 executes *command1*, directing the standard error stream to *file1*. 
  1030 
  1010 
  1031 
  1011 
  1032 
       
  1033 Another useful capability is to redirect one standard file handle to another. The most popular variation is to merge standard error into standard output so error messages can be processed together with (or alternately to) the usual output. Example:
       
  1034 ::
       
  1035 
       
  1036 	$ find / -name .profile > results 2>&1
       
  1037 
       
  1038 will try to find all files named *.profile*. Executed without redirection, it will output hits to *stdout* and errors (e.g. for lack of privilege to traverse protected directories) to *stderr*. If standard output is directed to file results, error messages appear on the console. To see both hits and error messages in file results, merge *stderr* (handle 2) into *stdout* (handle 1) using 2>&1 .
       
  1039 
       
  1040 It's possible use 2>&1 before ">" but it doesn't work. In fact, when the interpreter reads 2>&1, it doesn't know yet where standard output is redirected and then standard error isn't merged.
       
  1041 
       
  1042 If the merged output is to be piped into another program, the file merge sequence 2>&1 must precede the pipe symbol, thus:
       
  1043 ::
       
  1044 
  1012 
  1045 	$ find / -name .profile 2>&1 | less
  1013 	$ find / -name .profile 2>&1 | less
  1046 
  1014 
  1047 A simplified form of the command:
  1015 
  1048 ::
       
  1049 
       
  1050 	$ command > file 2>&1
       
  1051 
       
  1052 is:
       
  1053 ::
       
  1054 
       
  1055 	$ command &>file
       
  1056 
       
  1057 or:
       
  1058 ::
       
  1059 
       
  1060 	$command >&file
       
  1061 
  1016 
  1062 Chained pipelines
  1017 Chained pipelines
  1063 ------------------
  1018 ------------------
  1064 
  1019 
  1065 The redirection and piping tokens can be chained together to create complex commands. For example:
  1020 The redirection and piping tokens can be chained together to create complex commands. For example:
  1077 
  1032 
  1078 	$ ls -lrt | tee xyz
  1033 	$ ls -lrt | tee xyz
  1079 
  1034 
  1080 This directs the file list output to both standard output as well as to the file *xyz*.
  1035 This directs the file list output to both standard output as well as to the file *xyz*.
  1081 
  1036 
  1082 More Text Processing
  1037 
  1083 ====================
  1038 
       
  1039 Shell Meta Characters
       
  1040 ======================
       
  1041 
       
  1042 Unix recognizes certain special characters, called "meta characters," as command directives. The shell meta characters are recognized anywhere they appear in the command line, even if they are not surrounded by blank space. For that reason, it is safest to only use the characters A-Z, a-z, 0-9, and the period, dash, and underscore characters when naming files and directories on Unix. If your file or directory has a shell meta character in the name, you will find it difficult to use the name in a shell command.
       
  1043 
       
  1044 The shell meta characters include:
       
  1045 
       
  1046 \ / < > ! $ % ^ & * | { } [ ] " ' ` ~ ; 
       
  1047 
       
  1048 
       
  1049 As an example,
       
  1050 ::
       
  1051 
       
  1052 	$ ls file.*
       
  1053 
       
  1054 run on a directory containing the files file, file.c, file.lst, and myfile would list the files file.c and file.lst. However,::
       
  1055 
       
  1056 	$ ls file.?
       
  1057 
       
  1058 run on the same directory would only list file.c because the ? only matches one character, no more, no less. This can save you a great deal of typing time. For example, if there is a file called california_cornish_hens_with_wild_rice and no other files whose names begin with 'c', you could view the file without typing the whole name by typing this::
       
  1059 
       
  1060 	$ more c*
       
  1061 
       
  1062 because the c* matches that long file name.
       
  1063 
       
  1064 filenames containing metacharacters can pose many problems and should never be intentionally created.
       
  1065 
       
  1066 
       
  1067 
  1084 
  1068 
  1085 grep
  1069 grep
  1086 -----
  1070 -----
  1087 
  1071 
  1088 *grep* is a command line text search utility originally written for Unix. The name is taken from the first letters in *global / regular expression / print*, a series of instructions for the *ed* text editor. The *grep* command searches files or standard input globally for lines matching a given regular expression, and prints them to the program's standard output.
  1072 *grep* is a command line text search utility originally written for Unix. The name is taken from the first letters in *global / regular expression / print*, a series of instructions for the *ed* text editor. The *grep* command searches files or standard input globally for lines matching a given regular expression, and prints them to the program's standard output.
  1197       $grep user * | cut -d":"  -f1|uniq
  1181       $grep user * | cut -d":"  -f1|uniq
  1198 
  1182 
  1199 This returns list of all files which has the word user in it .
  1183 This returns list of all files which has the word user in it .
  1200 
  1184 
  1201 
  1185 
  1202 
  1186 Environment Variables:
       
  1187 ======================
       
  1188 
       
  1189 These variables like HOME, OSTYPE,Variables are a way of passing information from the shell to programs when you run them. Programs look "in the environment" for particular variables and if they are found will use the values stored. Standard UNIX variables are split into two categories, environment variables and shell variables. In broad terms, shell variables apply only to the current instance of the shell and are used to set short-term working conditions; environment variables have a farther reaching significance, and those set at login are valid for the duration of the session.By convention, environment variables have UPPER CASE and shell variables have lower case names.  
       
  1190 
       
  1191 Some of examples of Environment variables are: ::
       
  1192 
       
  1193    $ echo $OSTYPE 
       
  1194    linux-gnu
       
  1195    $ echo $HOME
       
  1196    /home/user 
       
  1197 
       
  1198 To see all the variables and there values use any of following commands: ::
       
  1199 
       
  1200    $ printenv | less
       
  1201    $ env
       
  1202 
       
  1203 The most commonly used environment variable is "PATH", it defines a list of directories to search through when looking for a command to execute. If you decide to put your own programs in a bin directory under your home directory, you'll have to modify the path to include that directory, or the system will never find your programs (unless you happen to be in that directory when you enter the command). Here's how to change your PATH variable so it includes your personal bin directory: ::
       
  1204 
       
  1205    $ set PATH=$PATH:$HOME/bin
       
  1206 
       
  1207 See the difference in value of PATH variable before and after modifying it. One can also create its own variable to make things easier: ::
       
  1208 
       
  1209    $ set repo = $HOME/Desktop/random/code
       
  1210    $ cd $repo
       
  1211 
       
  1212 *set* command is used to define a variable for the current shell. Try opening a new shell and use the above mentioned command, it wont work as expected. The other child process wont be able to see these variables unless we *export* them. Repeat the above mentioned activity with *export* command. Now with all new shells, *$repo* will work.
       
  1213 
       
  1214 
       
  1215 
       
  1216 
       
  1217 
       
  1218 Shell Scripting:
       
  1219 ================
       
  1220 
       
  1221 Basics:
       
  1222 -------
       
  1223 
       
  1224 Shell program or shell script,a sequence of commands to a text file and tell the shell to execute the text file instead of entering the commands. The first *"Hello World"* sample for shell scripting is as easy as it sounds: ::
       
  1225 
       
  1226    $ echo '#!/bin/sh' > my-script.sh
       
  1227    $ echo 'clear' >> my-script.sh   
       
  1228    $ echo 'echo Hello World' >> my-script.sh
       
  1229    $ chmod 755 my-script.sh
       
  1230    $ ./my-script.sh
       
  1231    Hello World
       
  1232 
       
  1233 The #! syntax(also known as shebang) is used in scripts to indicate an interpreter for execution under UNIX / Linux operating systems. The chmod is required to make the script executable. This script will just execute two commands, *clear* and *echo* one after another. One can also do the same task using a one liner command *clear; echo 'Hello World';* but as number of lines grows using a script file is helpful. 
       
  1234 
       
  1235 So lets create a script which gives us all the filenames for given initial alphabet or string in a directory. Let the name of script be *initial.sh*, open it with text editor, and write: ::
       
  1236 
       
  1237    #!/bin/sh
       
  1238    ls > temp
       
  1239    grep ^$1 < temp
       
  1240    rm temp
       
  1241    $ chmod a+x initial.sh
       
  1242    $ ./initial.sh s
       
  1243 
       
  1244 The $1 in the script is pertaining to command line argument. All arguments passed via command line are accessed via *$#* with name of script being first member, that is $0. Now lets write a script for finding a file, and then checking when was it last modified: ::
       
  1245 
       
  1246    #!/bin/sh
       
  1247    name=`find . -name $1 -print`
       
  1248    echo $name
       
  1249    last_modified=`stat -c %y $name| cut -f 1 -d " "`
       
  1250    echo "Last modified: $last_modified"    
       
  1251    $ ./search.sh fname
       
  1252 
       
  1253 Try giving some file you want to search in place of fname. Please note in second line *`* its a back-quote(other key mapped with tilda), it is specifically used to get the output of one command into a variable. In this particular case name is a User defined variables  which stores the value. We access value stored in any variable using *$* symbol before name of variable.
       
  1254 
       
  1255 
       
  1256 
       
  1257 Shell Arithmetic:
       
  1258 -----------------
       
  1259 
       
  1260 Shell also provides support for basic arithmetic operations. The syntax is: ::
       
  1261 
       
  1262    $ expr op1 math-operator op2
       
  1263 
       
  1264 Some of example which can be tried handily: ::
       
  1265    
       
  1266    $ expr -3 + 5
       
  1267    2
       
  1268    $ expr 10 % 3
       
  1269    1
       
  1270 
       
  1271 These spaces in between operator and operands is important, without them shell interpreter will raise the syntax error. ::
       
  1272 
       
  1273    $ expr 2*3
       
  1274    expr: syntax error
       
  1275    
       
  1276 One can use back-quotes(`) also to get value of expr. ::
       
  1277 
       
  1278    $ echo `expr 6 + 3`
       
  1279    9
       
  1280    $ result=`expr 6 + 3`
       
  1281    $ echo $result
       
  1282    9
       
  1283 
       
  1284 Shell uses three kinds of quotes. Double quotes("), anything enclosed among them except from variable trailing after $, and characters after \ would be printed as it is. Single quotes('), anything enclosed within them is just same, no formulation/interpretation. Back quotes(`), anything inclosed is considered as command, or is executed. ::
       
  1285 
       
  1286    $ echo "Today is date"
       
  1287    Today is date
       
  1288    $ echo "Today is `date`"
       
  1289    Today is Wed Sep 16 17:32:22 IST 2009
       
  1290    $ echo 'Today is `date`'
       
  1291    Today is `date`
       
  1292    $ echo "Today is \n `date`"
       
  1293    Today is \n Wed Sep 16 17:40:13 IST 2009
       
  1294    $ echo -e "Today is \n `date`"
       
  1295    Today is 
       
  1296     Wed Sep 16 17:41:13 IST 2009 
       
  1297 
       
  1298 if else construct:
       
  1299 ------------------
       
  1300 
       
  1301 One can have simple *if else if* constructs in shell scripts to check conditions. Lets take simple example of writing a script which returns back whether the argument passed is positive or not: ::
       
  1302 
       
  1303    #!/bin/sh
       
  1304    if test $1 -gt 0
       
  1305    then
       
  1306      echo "number is positive"
       
  1307    else
       
  1308      echo "number is negative"
       
  1309    fi
       
  1310    $ ./sign.sh -11
       
  1311    number is negative
       
  1312 
       
  1313 This script will compare the first value passed as argument with 0 *if test var -gt val*, var being $1 and val being 0, gt meaning greater then. Now this program has some flaw, it will give same result for following input: (-11) and (-1, 5), as we are checking just $1 which is first argument and hence the result. For handling such situation we can include *if-else* clause which will warn user of correct usage of script. ::
       
  1314 
       
  1315    #this is the case when no argument is passed  
       
  1316    if [ $# -eq 0 ]
       
  1317    then
       
  1318      echo "$0 : You must give/supply one integers"
       
  1319      exit 1
       
  1320    else 
       
  1321      if [ $# -gt 1 ]
       
  1322      then
       
  1323        echo "$0 : You must give one integer"
       
  1324        exit 1
       
  1325      fi
       
  1326    fi
       
  1327 
       
  1328 One important thing to note in shell script is spacing, with many comparison and evaluation operation a wrongly placed space will spoil all the fun. So in previous example the expression *[ $# -eq 0 ]* will work properly, but if we remove those leading or trailing spaces like *[ $# -eq 0]*, it wont work as expected, or rather throw a warning. Both *test* and *[]* do the same task of testing a expression and returning true or false.
       
  1329 
       
  1330 Lets create something interesting using these if-else clause. Now we will create a script which will greet the user when he opens the shell. We will create the script, change the permission to make it executable and append the *.bashrc* file with *./greet.sh* line and we are done. The script is: ::
       
  1331 
       
  1332    #!/bin/sh
       
  1333    #Script to greet the user according to time of day
       
  1334    temph=`date | cut -c12-13`
       
  1335    dat=`date +"%A %d in %B of %Y (%r)"`
       
  1336    if [ $temph -lt 12 ]
       
  1337    then
       
  1338      mess="Good Morning $LOGNAME, Have a nice day!"
       
  1339    fi
       
  1340 
       
  1341    if [ $temph -gt 12 -a $temph -le 16 ]
       
  1342    then
       
  1343      mess="Good Afternoon $LOGNAME"
       
  1344    fi
       
  1345 
       
  1346    if [ $temph -gt 16 -a $temph -le 18 ]
       
  1347    then
       
  1348      mess="Good Evening $LOGNAME"
       
  1349    fi
       
  1350    echo -e "$mess\nThis is $dat"
       
  1351 
       
  1352 For me when I open the shell the output is something like: ::
       
  1353 
       
  1354    Good Morning user, Have a nice day!
       
  1355    This is Wednesday 16 in September of 2009 (11:54:47 AM IST) 
       
  1356 
       
  1357 Loops
       
  1358 -----
       
  1359 
       
  1360 Bash has three different commands for looping -- ``for``, ``while`` and ``until``. 
       
  1361 
       
  1362 ``for`` loop
       
  1363 ~~~~~~~~~~~~
       
  1364 
       
  1365 Suppose we have a set of files, that have names beginning with numbers followed by their names - ``08 - Society.mp3``. We would like to rename these files to remove the numbering. How would we go about doing that? It is clear from the problem statement that we could use a ``for`` loop, to loop through the list of files and rename each of the files.  
       
  1366 
       
  1367 Let's first look at a simple ``for`` loop, to understand how it works. 
       
  1368 ::
       
  1369 
       
  1370   for animal in rat cat dog man
       
  1371   do 
       
  1372     echo $animal
       
  1373   done
       
  1374 
       
  1375 We just wrote a list of animals, each animal's name separated by a space and printed each name on a separate line. The variable ``animal`` is a dummy variable and has no significance. You could use something as lame as ``i`` in place of ``animal``.  
       
  1376 
       
  1377 Now, we use a simple ``for`` loop to list the files that we are interested in. 
       
  1378 ::
       
  1379 
       
  1380   ls *.mp3 > list
       
  1381   for i in `cat list`
       
  1382   do
       
  1383     echo "$i"
       
  1384   done
       
  1385 
       
  1386 If your filenames contain spaces, ``for`` assumes each space separated word to be a single item in the list and prints it in a separate line. We could change the script slightly to overcome this problem. 
       
  1387 ::
       
  1388 
       
  1389   for i in *.mp3
       
  1390   do
       
  1391     echo "$i"
       
  1392   done
       
  1393 
       
  1394 Now, we have each file printed on a separate line. Depending on the files that we have we could use grep to get the relevant portion of the filenames and rename the files. 
       
  1395 ::
       
  1396 
       
  1397   for i in *.mp3
       
  1398   do 
       
  1399     j=$(echo "$i"|grep -o "[A-Za-z'&. ]*.mp3")
       
  1400     echo "$i -> $j"
       
  1401   done
       
  1402 
       
  1403 Now we just replace the echo command with a ``mv``  command. 
       
  1404 ::
       
  1405 
       
  1406   for i in *.mp3
       
  1407   do 
       
  1408     j=$(echo "$i"|grep -o "[A-Za-z'&. ]*.mp3")
       
  1409     mv "$i" "$j"
       
  1410   done
       
  1411 
       
  1412 
       
  1413 
       
  1414 ``while``
       
  1415 ~~~~~~~~~
       
  1416 
       
  1417 The ``while`` command allows us to continuously execute a block of commands until the command that is controlling the loop is executing successfully. 
       
  1418 
       
  1419 Let's start with the lamest example of a while loop.
       
  1420 ::
       
  1421 
       
  1422   while true
       
  1423   do
       
  1424     echo "True"
       
  1425   done
       
  1426 
       
  1427 This, as you can see, is an infinite loop that prints the ``True``. 
       
  1428 
       
  1429 Say we wish to write a simple program that takes user input and prints it back, until the input is ``quit``, which quits the program. 
       
  1430 ::
       
  1431 
       
  1432   while [ "$variable" != "quit" ]
       
  1433   do
       
  1434     read variable
       
  1435     echo "Input - $variable"
       
  1436   done
       
  1437   exit 0
       
  1438 
       
  1439 ``until``
       
  1440 ~~~~~~~~~
       
  1441 
       
  1442 The ``until`` loop is similar to the ``while`` loop, except that it executes until the conditional command does not execute properly. 
       
  1443 
       
  1444 The infinite loop changes to the following, when ``until`` is used.
       
  1445 ::
       
  1446 
       
  1447   until false
       
  1448   do
       
  1449     echo "True"
       
  1450   done
       
  1451 
       
  1452 Now lets try and use these above mentioned options provided by shell to write a utility. Until now, when we try find or locate it looks through directories and files for result. But they wont search through tar archives and zipped files. Lets create a shell script for especially looking through these files
       
  1453 ::
       
  1454 
       
  1455   #!/bin/sh
       
  1456 
       
  1457   #To check number of arguments being passed.
       
  1458   if [ $# -eq 0 ] ; then
       
  1459   echo "Correct usage: $0 tar-archive filename \nOr $0 filename"
       
  1460   exit 1
       
  1461   else
       
  1462     if [ $# -eq 1 ] ; then
       
  1463       tar_archive=`find $PWD -name "*.tar*"`
       
  1464     else
       
  1465       tar_archive=`find $PWD -name $1`
       
  1466     fi
       
  1467   fi
       
  1468 
       
  1469   #Search of particular file inside archives.
       
  1470   for archive in $tar_archive
       
  1471   do
       
  1472     echo $archive
       
  1473     variable=`tar -tf $archive`
       
  1474     for word in $variable
       
  1475     do
       
  1476       if [ $# -eq 1 ] ; then
       
  1477         echo "$word" | grep -q ".*$1"
       
  1478       else
       
  1479 	echo "$word" | grep -q ".*$2"
       
  1480       fi
       
  1481     if [ $? -eq 0 ] ; then 
       
  1482       echo "File present in $archive!" 
       
  1483     fi  
       
  1484     done
       
  1485   done
       
  1486 
       
  1487 
       
  1488 Functions
       
  1489 ---------
       
  1490 
       
  1491 When a group of commands are repeatedly being used within a script, it is convenient to group them as a function. This saves a lot of time and you can avoid retyping the code again and again. Also, it will help you maintain your code easily. Let's see how we can define a simple function, ``hello-world``. Function can be defined by using function name followed by a pair of parentheses. 
       
  1492 ::
       
  1493 
       
  1494   
       
  1495   hello-world () {
       
  1496     echo "Hello, World.";
       
  1497   }
       
  1498 
       
  1499   $ hello-world
       
  1500   Hello, World.
       
  1501 
       
  1502 Passing parameters to functions is similar to passing them to scripts. 
       
  1503 ::
       
  1504 
       
  1505 
       
  1506   #! /bin/bash
       
  1507 
       
  1508   hello-name()
       
  1509   {
       
  1510      echo  "hello ". $1
       
  1511         
       
  1512   }
       
  1513 
       
  1514   hello-name $1
       
  1515 
       
  1516 
       
  1517   #!usr/bin/bash
       
  1518   hello-name
       
  1519   { 
       
  1520   echo "Hello, $1."; 
       
  1521   }
       
  1522 
       
  1523   hello-name $1
       
  1524 
       
  1525   save this in a file helloscipt.sh and give it execute permission
       
  1526   
       
  1527 
       
  1528   $ ./helloscipt 9
       
  1529   Hello, 9.
       
  1530 
       
  1531 Any variables that you define within a function, will be added to the global namespace. If you wish to define variables that are restricted to the scope of the function, define a variable using the ``local`` built-in command of bash.
       
  1532 
       
  1533   
       
  1534 We shall now write a function for the word frequency generating script that we had looked at in the previous session. 
       
  1535 
       
  1536 ::
       
  1537 
       
  1538   word_frequency() {
       
  1539     if [ $# -ne 1 ]
       
  1540     then
       
  1541       echo "Usage: $0 file_name"
       
  1542       exit 1
       
  1543     else 
       
  1544       if [ -f "$1" ]
       
  1545       then
       
  1546         grep  "[A-Za-z]*" -o "$1" | tr 'A-Z' 'a-z' | sort | uniq -c | sort -nr | less
       
  1547       fi
       
  1548     fi
       
  1549   }
       
  1550 
       
  1551  word_frequency  $1
       
  1552 
       
  1553 
       
  1554 
       
  1555 	
       
  1556