Sie sind auf Seite 1von 68

File prompting commands...................................................................................................3 ls.......................................................................................................................................3 ls is a command to list files in Unix and Unix-like operating systems........................

3 Open Last Edited File Using ls t................................................................................3 Display One File Per Line Using ls -1 ......................................................................4 Display All Information About Files/Directories Using ls l......................................4 Display File Size in Human Readable Format Using ls -lh........................................5 Display Directory Information Using ls -ld................................................................5 Order Files Based on Last Modified Time Using ls -lt...............................................5 Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr..............6 Display Files Recursively Using ls -R........................................................................7 Display File Inode Number Using ls -i.......................................................................7 Display File UID and GID Using ls -n.......................................................................8 Visual Classification of Files With Special Characters Using ls -F...........................8 Visual Classification of Files With Colors Using ls -F................................................9 Useful ls Command Aliases........................................................................................9 cd......................................................................................................................................9 Examples of the cd command....................................................................................10 cd ../home/users/computerhope.................................................................................10 cd ../../.........................................................................................................................10 Using wildcards.........................................................................................................10 Back to the previous directory...................................................................................11 Mkdir..............................................................................................................................11 How to create one directory.......................................................................................11 How to create multiple directories at one time..........................................................11 To create nested directory..........................................................................................11 Pwd................................................................................................................................12 Head:..............................................................................................................................12 Tail:................................................................................................................................12 More:..............................................................................................................................12 Options...................................................................................................................13 Less:...............................................................................................................................14 Frequently used options.............................................................................................14 Frequently used commands........................................................................................15 Date:...............................................................................................................................15 |(pipe):............................................................................................................................16 Grep:..............................................................................................................................16 Search for the given string in a single file.................................................................17 Checking for the given string in multiple files..........................................................18 Case insensitive search using grep i.........................................................................18 Match regular expression in files...............................................................................18 Checking for full words, not for sub-strings using grep -w.......................................19 Searching in all files recursively using grep r..........................................................20

Display the lines which does not matches all the given pattern................................20 Counting the number of matches using grep c.........................................................20 Display only the file names which matches the given pattern using grep l.............21 Show only the matched string....................................................................................21 Show the position of match in the line.......................................................................21 Removing a file or directory:.........................................................................................22 To remove a file.........................................................................................................22 To remove an empty directory...................................................................................22 To remove directory recursively & forcefully...........................................................22 Copying a file:................................................................................................................22 To move a file or directory............................................................................................22 To rename a file or directory.........................................................................................22 Creation of file:..............................................................................................................23 vi-editor......................................................................................................................23 Command mode:....................................................................................................24 Execute mode:........................................................................................................24 Substitutions ..................................................................................................................32 File Permissions.............................................................................................................32 Symbolic mode:.........................................................................................................32 Absolute mode:..........................................................................................................33 LINKS:...........................................................................................................................33 To Configure Hard Link............................................................................................34 To Configure Soft Link..............................................................................................34 Disk Management..............................................................................................................34 fdisk................................................................................................................................34 fdisk l:......................................................................................................................34 df h:..............................................................................................................................34 du:..................................................................................................................................35 Process Stat:.......................................................................................................................36 To print a process tree:...................................................................................................38 To get info about threads:..............................................................................................38 To terminate a process:..................................................................................................38 To kill parent ID:...........................................................................................................38 To view entire network process:....................................................................................39 Network Printing:...............................................................................................................39 To give a file for print....................................................................................................39 To remove a print query from list..................................................................................39 Network Basics..................................................................................................................39 To check IP address and IP information........................................................................39 To check network connectivity:.....................................................................................39 To check LAN card status:............................................................................................40 To check host name:......................................................................................................40 nslookup.........................................................................................................................41 Using subcommands:.................................................................................................41 Uname............................................................................................................................42 Print name of current system.....................................................................................42

Print the name of the hardware implementation (platform).......................................42 Traceroute......................................................................................................................42 Remote Filesharing:...........................................................................................................43 rsync: .............................................................................................................................43 scp:.................................................................................................................................43 Logging to the machine:....................................................................................................44 rlogin..............................................................................................................................44 rsh...................................................................................................................................44 User commands..................................................................................................................45 Sorting output of the ps command.............................................................................48 Sorting file contents...................................................................................................48 Examples....................................................................................................................50 OPTIONS...................................................................................................................51 Examples:...................................................................................................................51 Job related commands........................................................................................................58 File archiving commands...................................................................................................60 Finding things....................................................................................................................62 Search for file with a specific name in a set of files (-name) ...................................62 How to search for a string in a selection of files (-exec grep ...). .............................63 Search in case insensitive mode.................................................................................65 Search files by size.....................................................................................................65 How to find directories with find...............................................................................65 Finding files that contain text (find plus grep)...........................................................65 which:.............................................................................................................................66 Whereis:.........................................................................................................................66 . Executing a background job.....................................................................................67 2. Sending the current foreground job to the background using CTRL-Z and bg command....................................................................................................................67 3. View all the background jobs using jobs command..............................................67 4. Taking a job from the background to the foreground using fg command.............67 5. Kill a specific background job using kill %...........................................................68

File prompting commands


ls
ls is a command to list files in Unix and Unix-like operating systems.

Open Last Edited File Using ls t


To open the last edited file in the current directory use the combination of ls, head and vi commands as shown below.

ls -t sorts the file by modification time, showing the last edited file first. head -1 picks up this first file.
$ vi first-long-file.txt $ vi second-long-file.txt $ vi `ls -t | head -1`

[Note: This will open the last file you edited (i.e second-long-file.txt)]

Display One File Per Line Using ls -1


To show single entry per line, use -1 option as shown below.
$ ls -1 bin boot cdrom dev etc home initrd initrd.img

Display All Information About Files/Directories Using ls l


To show long listing information about the file/directory.
$ ls -l

-rw-r----- 1 ramesh team-dev 9275204 Jun 13 15:27 mthesaur.txt.gz

1st Character File Type (i.e.: -): First character specifies the type of the file. In the example above the hyphen (-) in the 1st character indicates that this is a normal file. Following are the possible file type options in the 1st character of the ls -l output. o Field Explanation o - normal file o d directory o s socket file o l link file Field 1 File Permissions (i.e.: rw-r-----): Next 9 character specifies the files permission. Each 3 characters refers to the read, write, execute permissions for

user, group and world In this example, -rw-r indicates read-write permission for user, read permission for group, and no permission for others. Field 2 Number of links (i.e.: 1): Second field specifies the number of links for that file. In this example, 1 indicates only one link to this file. Field 3 Owner (i.e.: ramesh): Third field specifies owner of the file. In this example, this file is owned by username ramesh. Field 4 Group (i.e.: team-dev): Fourth field specifies the group of the file. In this example, this file belongs to team-dev group. Field 5 Size (i.e.: 9275204): Fifth field specifies the size of file. In this example, 9275204 indicates the file size. Field 6 Last modified date & time: Sixth field specifies the date and time of the last modification of the file. In this example, Jun 13 15:27 specifies the last modification time of the file. Field 7 File name (i.e.: mthesaur.txt.gz): The last field is the name of the file. In this example, the file name is mthesaur.txt.gz.

Display File Size in Human Readable Format Using ls -lh


Use ls -lh (h stands for human readable form), to display file size in easy to read format. i.e M for MB, K for KB, G for GB.
$ ls -l -rw-r----- 1 ramesh team-dev 9275204 Jun 12 15:27 arch-linux.txt.gz* $ ls -lh -rw-r----- 1 ramesh team-dev 8.9M Jun 12 15:27 arch-linux.txt.gz

Display Directory Information Using ls -ld


When you use ls -l you will get the details of directories content. But if you want the details of directory then you can use -d option as., For example, if you use ls -l /etc will display all the files under etc directory. But, if you want to display the information about the /etc/ directory, use -ld option as shown below.
$ ls -l /etc total 3344 -rw-r--r--rw-r--r-drwxr-xr-x -rw-r--r-drwxr-xr-x

1 1 4 1 4

root root root root root

root root root root root

15276 2562 4096 48 4096

Oct Oct Feb Feb Feb

5 5 2 8 2

2004 2004 2007 2008 2007

a2ps.cfg a2ps-site.cfg acpi adjtime alchemist

$ ls -ld /etc drwxr-xr-x 21 root root 4096 Jun 15 07:02 /etc

Order Files Based on Last Modified Time Using ls -lt

To sort the file names displayed in the order of last modification time use the -t option. You will be finding it handy to use it in combination with -l option.
$ ls -lt total 76 drwxrwxrwt 14 root root 4096 Jun drwxr-xr-x 121 root root 4096 Jun drwxr-xr-x 13 root root 13780 Jun drwxr-xr-x 13 root root 4096 Jun drwxr-xr-x 12 root root 4096 Jun drwxr-xr-x 2 root root 4096 May lrwxrwxrwx 1 root root 11 May drwx-----2 root root 16384 May drwxr-xr-x 15 root root 4096 Jul

22 22 22 20 18 17 17 17 2

07:36 07:05 07:04 23:12 08:31 21:21 20:29 20:29 2008

tmp etc dev root home sbin cdrom -> media/cdrom lost+found var

Order Files Based on Last Modified Time (In Reverse Order) Using ls -ltr
To sort the file names in the last modification time in reverse order. This will be showing the last edited file in the last line which will be handy when the listing goes beyond a page. This is my default ls usage. Anytime I do ls, I always use ls -ltr as I find this very convenient.
$ ls -ltr total 76 drwxr-xr-x 15 root drwx-----2 root lrwxrwxrwx 1 root drwxr-xr-x 2 root drwxr-xr-x 12 root drwxr-xr-x 13 root drwxr-xr-x 13 root drwxr-xr-x 121 root drwxrwxrwt 14 root root 4096 Jul 2 2008 var root 16384 May 17 20:29 lost+found root 11 May 17 20:29 cdrom -> media/cdrom root 4096 May 17 21:21 sbin root 4096 Jun 18 08:31 home root 4096 Jun 20 23:12 root root 13780 Jun 22 07:04 dev root 4096 Jun 22 07:05 etc root 4096 Jun 22 07:36 tmp

To show all the hidden files in the directory, use -a option. Hidden files in Unix starts with . in its file name.
$ ls -a [rnatarajan@asp-dev ~]$ ls -a . Debian-Info.txt .. CentOS-Info.txt .bash_history Fedora-Info.txt .bash_logout .lftp .bash_profile libiconv-1.11.tar.tar .bashrc libssh2-0.12-1.2.el4.rf.i386.rpm

It will show all the files including the . (current directory) and .. (parent directory). To show the hidden files, but not the . (current directory) and .. (parent directory), use option -A.
$ ls -A Debian-Info.txt Fedora-Info.txt CentOS-Info.txt Red-Hat-Info.txt .bash_history SUSE-Info.txt .bash_logout .lftp .bash_profile libiconv-1.11.tar.tar .bashrc libssh2-0.12-1.2.el4.rf.i386.rpm [Note: . and .. are not displayed here]

Display Files Recursively Using ls -R

To show all the files recursively, use -R option. When you do this from /, it shows all the unhidden files in the whole file system recursively.

Display File Inode Number Using ls -i


Sometimes you may want to know the inode number of a file for internal maintenance. Use -i option as shown below to display inode number. Using inode number you can remove files that has special characters in its name as explained in the example#6 of the find command article.

Display File UID and GID Using ls -n


Lists the output like -l, but shows the uid and gid in numeric format instead of names.
$ ls -l ~/.bash_profile -rw-r--r-- 1 ramesh ramesh 909 Feb 8 11:48 /home/ramesh/.bash_profile $ ls -n ~/.bash_profile -rw-r--r-- 1 511 511 909 Feb 8 11:48 /home/ramesh/.bash_profile [Note: This display 511 for uid and 511 for gid]

Visual Classification of Files With Special Characters Using ls -F


Instead of doing the ls -l and then the checking for the first character to determine the type of file. You can use -F which classifies the file with different special character for different kind of files.
$ ls -F Desktop/ Documents/ Templates/ Ubuntu-App@ firstfile Music/ Public/

Thus in the above output,


/ directory. nothing normal file. @ link file. * Executable file

Visual Classification of Files With Colors Using ls -F


Recognizing the file type by the color in which it gets displayed is an another kind in classification of file. In the above output directories get displayed in blue, soft links get displayed in green, and ordinary files gets displayed in default color.
$ ls --color=auto Desktop Documents Examples firstfile Music Templates Videos Pictures Public

Useful ls Command Aliases


You can take some required ls options in the above, and make it as aliases. We suggest the following.

Long list the file with size in human understandable form.


alias ll="ls -lh"

Classify the file type by appending special characters.


alias lv="ls -F"

Classify the file type by both color and special character.


alias ls="ls -F --color=auto"

cd
About cd Changes the directory. Syntax cd [directory] directory Name of the directory user wishes to enter. cd .. cd Used to go back one directory on the majority of all Unix shells. It is important that the space be between the cd and the .. When in a Korn shell to get back one directory used to go back one directory.

Examples of the cd command


This first command moves you to the /usr directory. The /usr directory becomes your current working directory:
cd /usr

Similarly, this command moves you to the /tmp directory:


cd /tmp

You don't have to move just one directory at a time though. You can easily jump from one directory to another directory far, far away, like this:
cd /var/www/html/unix/edu

cd ../home/users/computerhope
The above example would go back one directory and then go into the home/users/computerhope directory.

cd ../../
Next, the above example would go back two directories. cd Finally, typing just cd alone will move you into the home directory.

Using wildcards
You can also use wildcard characters when moving between directories. This next command works just like the previous command, taking me to the /var/www/html/unix/edu directory on my Unix system:
cd /v*/w*/h*/u*/e*

The wildcard characters can be interpreted as "any number of any character", so the Linux system expands the /v/w/h/u/e that I typed into /var/www/html/unix/edu.

Back to the previous directory


Again, with every Unix and Linux shell I've worked with, you can also always move back to your previous directory by adding a hyphen after the cd command, like this:
cd -

This is a great feature for when you're moving back and forth between two different directories while working on a project.

Mkdir
The Unix/Linux/GNU mkdir command is used to create new directories (sub-directories).

How to create one directory


This first example creates a new directory named tmp in your current directory. Ex: #mkdir tmp This example assumes that you have the proper permissions to create a new sub-directory in your current working directory.

How to create multiple directories at one time


This command creates three new sub-directories (memos, letters, and e-mail) in the current directory. Ex: #mkdir memos letters e-mail

To create nested directory


mkdir -p <dir1/dir2/dir3> mkdir -p sun/moon/stars

Pwd
In Unix-like and some other operating systems the pwd command (print working directory) is used to output the path of the current working directory. Example: $ pwd /home/foobar

Head:
Used to view first ten lines of a file Syntax: head <filename> Ex: head /etc/passwd Syntax2: head n <no of lines> <filename> Ex: head n 5 /etc/passwd (To view 5 lines of a file)

Tail:
Used to view last ten lines of a file Syntax: tail <filename> Ex: tail /etc/passwd Ex: tail n 20 /etc/passwd (to view last 20 lines of a file)

More:
Used to see the content page wise but we cannot scroll up

If no file name is provided, more looks for input from stdin. 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. Syntax: more <filename> Ex: more /etc/passwd

Options
Options are typically entered before the file name, but can also be entered in the environment variable $MORE. Options entered in the actual command line will override those entered in the $MORE environment variable. Available options may vary between Unix systems, but a typical set of options is as follows:

-num: This option specifies an integer which is the screen size (in lines). -d: more will prompt the user with the message "[Press space to continue, 'q' to quit.]" and will display "[Press 'h' for instructions.]" instead of ringing the bell when an illegal key is pressed. -l: more usually treats ^L (form feed) as a special character, and will pause after any line that contains a form feed. The -l option will prevent this behavior. -f: Causes more to count logical, rather than screen lines (i.e., long lines are not folded). -p: Do not scroll. Instead, clear the whole screen and then display the text. -c: Do not scroll. Instead, paint each screen from the top, clearing the remainder of each line as it is displayed. -s: Squeeze multiple blank lines into one. -u: Suppress underlining. +/: The +/ option specifies a string that will be searched for before each file is displayed. (Ex.: more +/Preamble gpl.txt) +num: Start at line number num.

Examples more +3 myfile.txt

In the above example the command would begin displaying the file myfile.txt at line three. To display the file named letter.txt on the screen, the user can type either of the following two commands: more < letter.txt type letter.txt | more The command displays the first screen of information from letter.txt, and then the following prompt appears: -- More -When the spacebar is pressed, the next screen of information will be displayed. It is also possible to clear the screen and remove all extra blank lines before displaying the file:
more /c /s < letter.txt type letter.txt | more /c /s

Less:
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.
Syntax: less [options] file_name

Ex: less /etc/passwd Ex: less -M readme.txt


#Read "readme.txt."

Frequently used options


-g:

Highlights just the current match of any searched string. -I: Case-insensitive searches. -M: Shows more detailed prompt, including file position. -N: Shows line numbers (useful for source code viewing). -S: Disables line wrap ("chop long lines"). Long lines can be seen by side scrolling.

-?: Shows help.

Frequently used commands


[Arrows]/[Page Up]/[Page Down]/[Home]/[End]: Navigation. [Space bar]: Next page. b: Previous page. ng: Jump to line number n. Default is the start of the file. nG: Jump to line number n. Default is the end of the file. /pattern: Search for pattern. Regular expressions can be used. [/ = slash] Press / and then Enter to repeat the previous search pattern. n: Go to next match (after a successful search). N: Go to previous match. mletter: Mark the current position with letter. 'letter: Return to position letter. [' = single quote] '^ or g: Go to start of file. '$ or G: Go to end of file. s: Save current content (got from another program like grep) in a file. =: File information. F: continually read information from file and follow its end. Useful for logs watching. Use Ctrl+C to exit this mode. -option: Toggle command-line option -option. h: Help. q: Quit.

Date:
Used to view current date & time. To change date Syntax: date <mm-dd-hr-min-year> Ex: date 042711452010 It means 04 month 27 date 11:45 2010 year

|(pipe):
The symbol | is the Unix pipe symbol that is used on the command line. What it means is that the standard output of the command to the left of the pipe gets sent as standard input of the command to the right of the pipe. Note that this functions a lot like the > symbol used to redirect the standard output of a command to a file. However, the pipe is different because it is used to pass the output of a command to another command, not a file. Here is an example:
$ cat apple.txt core worm seed jewel $ cat apple.txt | wc 3 4 21 $

In this example, at the first shell prompt, I show the contents of the file apple.txt to you. In the next shell prompt, I use the cat command to display the contents of the apple.txt file, but I sent the display not to the screen, but through a pipe to the wc (word count) command. The wc command then does its job and counts the lines, words, and characters of what it got as input. You can combine many commands with pipes on a single command line. Here's an example where I count the characters, words, and lines of the apple.txt file, then mail the results to nobody@december.com with the subject line "The count."
$ cat apple.txt | wc | mail -s "The count" nobody@december.com

Grep:
Grep is used to skip something specially from the output Patterns for searching. . * Matches single character. Wild character Example C* if found would pull up CC or CAT...

{} ^ $ \

Matches any character contained within the bracket. Represents the beginning of the line, so if you did ^T it would search for any sentence starting with a T. Represents the end of the line, so if you did $. then it would pull up any lines that ended with . Means to take the next character serious so you could search for C\ C.

The Unix grep command helps you search for strings in a file. Here is how I can find the lines that contain the string "jewel" and display those lines to the standard output:
$ cat apple.txt core worm seed jewel $ grep jewel apple.txt jewel $

Examples:
First create the following demo_file that will be used in the examples below to demonstrate grep command.
$ cat demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. Two lines above this line is empty.

And this is the last line.

Search for the given string in a single file


The basic usage of grep command is to search for a specific string in the specified file as shown below.
Syntax:

#grep "literal_string" filename


$ grep "this" demo_file this line is the 1st lower case line in this file.

Two lines above this line is empty.

Checking for the given string in multiple files.


Syntax:

grep "string" FILE_PATTERN This is also a basic usage of grep command. For this example, let us copy the demo_file to demo_file1. The grep output will also include the file name in front of the line that matched the specific pattern as shown below. When the Linux shell sees the meta character, it does the expansion and gives all the files as input to grep.
$ cp demo_file demo_file1 $ grep "this" demo_* demo_file:this line is the 1st lower case line in this file. demo_file:Two lines above this line is empty. demo_file:And this is the last line. demo_file1:this line is the 1st lower case line in this file. demo_file1:Two lines above this line is empty. demo_file1:And this is the last line.

Case insensitive search using grep i.


Syntax:
grep -i "string" FILE

This is also a basic usage of the grep. This searches for the given string/pattern case insensitively. So it matches all the words such as the, THE and The case insensitively as shown below.
$ grep -i "the" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. And this is the last line.

Match regular expression in files.


Syntax:

grep "REGEX" filename

This is a very powerful feature, if you can use use regular expression effectively. In the following example, it searches for all the pattern that starts with lines and ends with empty with anything in-between. i.e To search lines[anything in-between]empty in the demo_file.
$ grep "lines.*empty" demo_file

Two lines above this line is empty.

From documentation of grep: A regular expression may be followed by one of several repetition operators:

? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. {n,m} The preceding item is matched at least n times, but not more than m times.

Checking for full words, not for sub-strings using grep -w


If you want to search for a word, and to avoid it to match the substrings use -w option. Just doing out a normal search will show out all the lines. The following example is the regular grep where it is searching for is. When you search for is, without any option it will show out is, his, this and everything which has the substring is.
$ grep -i "is" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Has All Its First Character Of The Word With Upper Case. Two lines above this line is empty. And this is the last line.

The following example is the WORD grep where it is searching only for the word is. Please note that this output does not contain the line This Line Has All Its First Character Of The Word With Upper Case, even though is is there in the This, as the following is looking only for the word is and not for this.

$ grep -iw "is" demo_file THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. Two lines above this line is empty. And this is the last line.

Searching in all files recursively using grep r


When you want to search in all the files under the current directory and its sub directory. -r option is the one which you need to use. The following example will look for the string logs in all the files in the current directory and all its subdirectory.
$ grep -r "logs" *

Display the lines which does not matches all the given pattern.
Syntax: grep -v -e "pattern" -e "pattern" $ cat test-file.txt a b c d $ grep -v -e "a" -e "b" -e "c" test-file.txt d

Counting the number of matches using grep c


When you want to count that how many lines matches the given pattern/string, then use the option -c. Syntax:
grep -c "pattern" filename ex: $ grep -c "go" demo_text 6

When you want do find out how many lines matches the pattern
$ grep -c this demo_file 3

When you want do find out how many lines that does not match the pattern
$ grep -v -c this demo_file

Display only the file names which matches the given pattern using grep l
If you want the grep to show out only the file names which matched the given pattern, use the -l (lower-case L) option. When you give multiple files to the grep as input, it displays the names of file which contains the text that matches the pattern, will be very handy when you try to find some notes in your whole directory structure.
$ grep -l this demo_* demo_file demo_file1

Show only the matched string


By default grep will show the line which matches the given pattern/string, but if you want the grep to show out only the matched string of the pattern then use the -o option. It might not be that much useful when you give the string straight forward. But it becomes very useful when you give a regex pattern and trying to see what it matches as
$ grep -o "is.*line" demo_file is line is the 1st lower case line is line is is the last line

Show the position of match in the line


When you want grep to show the position where it matches the pattern in the file, use the following options as
Syntax: grep -o -b "pattern" file $ cat temp-file.txt 12345 12345 $ grep -o -b "3" temp-file.txt 2:3 8:3

Note: The output of the grep command above is not the position in the line, it is byte offset of the whole file.

Removing a file or directory:


To remove a file
Syntax: rm <filename>

To remove an empty directory


Syntax: rmdir <dirname>

To remove directory recursively & forcefully


Syntax: rm rf (to delete directory without asking yes or no)

Copying a file:
Syntax: cp <source> <destination> Ex: cp file1 /etc/ (to copy a file)

Syntax: cp rf <source> <destination> (To copy entire directory along with subdirectories & files) Ex: cp rf sun /ds/dawn Syntax: cp a <source> <destination> (To copy a file or directory along with permissions) Ex: cp a Server /var/ftp/pub

To move a file or directory


Syntax: mv <source> <destination> Ex: mv file1 /sun/moon

To rename a file or directory


Syntax: mv <old name> <new name>

Creation of file:
To create a file we have 3 methods 1. touch 2. cat 3. vi

touch: with the help of touch command we can create an empty file.
Syntax: touch <filename> With this command we can create n number of files at a time. Ex: touch file1 file2 file3

cat: by using cat we can create data files


Syntax: cat > <filename> Ex: cat > file1 (Edit data) (Ctrl+d)(To save) To view content of a file Cat <filename> To add data in existing file Cat >> <existing filename> (type data) (Ctrl+d)

vi-editor
In vi editor we have 3 modes: 1) command mode 2) insert mode 3) execute mode In command mode we can copy, paste, delete, undo, redo, move, save&quit

In insert mode we can only edit data In execute mode we can set line numbers, delete line numbers, save&quit, quit with out saving, substitute data. To go insert mode from command mode i: insert text at current cursor position I: insert text at the beginning of cursor line a: append text after cursor position A: append text at the end of cursor line o: create a new line below cursor line and append text O: create a new line above cursor line and append text To move from insertmode to command mode press esc key

Command mode:
dd: to delete a line 5dd: to delete five lines yy: to copy a line 5yy: to copy five lines p: paste 10p: paste 10 times u: undo Ctrl+r: redo Shift+g or G: to move last line of file gg: to move first line of a file 10g: to move 10th line of a file Shift+zz: save & quit To move into execute mode from command mode press shift+:

Execute mode:
q: quit with out saving q!: quit with out saving forcefully wq: save&quit

wq!: save&quit forcefully :/<word> : to search for a particular word : 15 to jump into 15th line of a file set nu : to set line numbers for a file set nonu: to remove line numbers of a file Substitution Syntax : <beginingline>, <endingline> s /<oldchar>/<newchr>/g

or <Return> move cursor down one line [or down-arrow] * k [or up-arrow] move cursor up one line *
j

or <Backspace> move cursor left one character [or left-arrow] l or <Space> * move cursor right one character [or right-arrow] * 0 (zero) move cursor to start of current line (the one with the cursor) *
h

* $

move cursor to end of current line w move cursor to beginning of next word b move cursor back to beginning of preceding word :0<Return> or 1G move cursor to first line in file :n<Return> or nG move cursor to line n
:$<Return> or G

move cursor to last line in file

General Startup To use vi: vi filename To exit vi and save changes: ZZ or :wq To exit vi without saving changes: :q! To enter vi command mode: [esc]

Counts A number preceding any vi command tells vi to repeat that command that many times. Cursor Movement

move left (backspace)

move down

move up

move right (spacebar)

[return]

move to the beginning of the next line

last column on the current line

move cursor to the first column on the current line

move cursor to first nonblank column on the current line

move to the beginning of the next word or punctuation mark

move past the next space

move to the beginning of the previous word or punctuation mark

move to the beginning of the previous word, ignores punctuation

end of next word or punctuation mark

end of next word, ignoring punctuation

move cursor to the top of the screen

move cursor to the middle of the screen

L Screen Movement

move cursor to the bottom of the screen

move to the last line in the file

xG

move to line x

z+

move current line to top of screen

move current line to the middle of screen

z-

move current line to the bottom of screen

^F

move forward one screen

^B

move backward one line

^D

move forward one half screen

^U

move backward one half screen

^R

redraw screen ( does not work with VT100 type terminals )

^L

redraw screen ( does not work with Televideo terminals )

Inserting

replace character under cursor with next character typed

keep replacing character until [esc] is hit

insert before cursor

append after cursor

append at end of line

O Deleting

open line above cursor and enter append mode

delete character under cursor

dd

delete line under cursor

dw

delete word under cursor

db Copying Code

delete word before cursor

yy

(yank)'copies' line which may then be put by the p(put) command. Precede with a count for multiple lines.

Put Command brings back previous deletion or yank of lines, words, or characters

bring back before cursor

p Find Commands

bring back after cursor

finds a word going backwards

finds a word going forwards

finds a character on the line under the cursor going forward

finds a character on the line under the cursor going backwards

find a character on the current line going forward and stop one character before it

find a character on the current line going backward and stop one character before it

repeat last f, F, t, T

Miscellaneous Commands

repeat last command

undoes last command issued

undoes all commands on one line

xp

deletes first character and inserts after second (swap)

join current line with the next line

^G

display current line number

if at one parenthesis, will jump to its mate

mx

mark current line with character x

'x

find line marked with character x

NOTE: Marks are internal and not written to the file. Line Editor Mode Any commands form the line editor ex can be issued upon entering line mode.

To enter: type ':'

To exit: press[return] or [esc] ex Commands For a complete list consult the UNIX Programmer's Manual READING FILES copies (reads) filename after cursor in file currently editing

:r filename WRITE FILE

:w MOVING

saves the current file without quitting

:#

move to line #

:$ SHELL ESCAPE

move to last line of file

executes 'cmd' as a shell command.

:!'cmd'

Substitutions
:%s/old/new/g :.,$s/old/new/g :^,.s/old/new/g :& Substitutes old with new throughout the file Substitutes old with new from the current cursor position to the end of the file Substitutes old with new from the beginning of the file to the current cursor position Repeats the last substitute (:s) command

File Permissions

We can change permissions in two methods 1) symbolic mode 2) absolute mode (numeric mode)

Symbolic mode:

Users u=owner(user) g=group o=other

permissions r=read w=write x=execute

operators + =

chmode: is the command to change permissions Syntax: chmod <permissions> <file or dir name> Ex: chmod u=rwx, g=rx, o=rx ds (Here we are giving full permissions to owner, read & execute for group & others)

Absolute mode:
In absolute mode we have to provide permissions in numeric signs r=4 w=2 x=1 Syntax: <permissions of owner, group, other> <filename> Ex: chmod 755 ds (Here we are giving full permissions to owner, read & execute to group & others If we want remove total permissions for others Ex: chmod 750 ds

LINKS:
HARD LINK SOFT LINK

Original & link file inode number will Different It cannot be create across the partition If original file is deleted then also the Link file will be accessible Editing of original file will replicate in the linked file

Original & link file inodes will be same It can be created across the partition If the original file is deleted the link file will not be accessible Editing of original file will replicate the linked file

Size of hard link file is same as original file

Size of soft link file is smaller than Original file

To Configure Hard Link


Syntax: ln <source file> <destination file> Ex: ln /dev/sda /dev/sdb

To Configure Soft Link


Syntax: ln s <source file> <destination file> Ex: ln s /usr/king /root/soft

Disk Management
fdisk
fdisk is the command to create partitions. Hard disks can be divided into one or more logical disks called partitions.

fdisk l:
Is the command to view current partitions

df h:
Is the command to view mounted partitions along with mount points & free space

du:
Tells you how much space a file occupies. #du -s *.txt -s - Instead of the default output, report only the total sum for each of the specified files. Would report the size of each txt file in the current directory. Below is an example of the output.

#du -ch *.txt - Display the size of the txt files in a friendly size format listing as well as the total capacity of all the files combined.

mounting: mounting is a process to create a logical way to enter a partition


Ex: mkdir /mountdir mount: is the command use to view mounted partitions and to create mounting. Syntax: mount <partition> <mount point> Ex: mount /dev/sda13 /mountdir

Umount: is the command to clear mounting way.


Syntax: umount <mountpoint> Ex: umount /mountdir

Process Stat:
ps displays information about a selection of the active processes.

A process is an executing program identified by a unique PID (process identifier). To see information about your processes, with their associated PID and status, type
% ps

A process may be in the foreground, in the background, or be suspended. In general the shell does not return the UNIX prompt until the current process has finished executing. Some processes take a long time to run and hold up the terminal. Backgrounding a long process has the effect that the UNIX prompt is returned immediately, and other tasks can be carried out while the original process continues executing. The "ps" command (process statistics) lets you check the status of processes that are running on your Unix system. ps The ps command by itself shows minimal information about the processes you are running. Without any arguments, this command will not show information about other processes running on the system. ps -f The -f argument tells ps to supply full information about the processes it displays. In this example, ps displays full information about the processes you are running.

ps -e The -e argument tells the ps command to show every process running on the system. ps -ef The -e and -f arguments are normally combined like this to show full information about every process running on the system. This is probably the most often-used form of the ps command. ps -ef | more Because the output normally scrolls off the screen, the output of the ps -ef command is often piped into the more command. The more command lets you view one screenful of information at a time. ps -fu fred This command shows full information about the processes currently being run by the user named fred (the -u option lets you specify a username).

To see every process on the system using standard syntax:


Ex: #ps e Ex: #ps ef

To print a process tree:


Ex: #Ps ejH

To get info about threads:


Ex: #ps eLf

To terminate a process:
#kill <process ID> Ex: kill 2314 If the process wont killed you have to kill parent ID

To kill parent ID:


#kill -9 <parent ID> Ex: kill -9 1

To view entire network process:


#top

Network Printing:
To view current printing query:
Ex: #lpq

To give a file for print


Ex: #lpr <filename>

To remove a print query from list


Syntax: #lprm <print.no> Ex: lprm 4

Network Basics
To check IP address and IP information
Ex: #ifconfig

To check network connectivity:


Ex: #ping 192.168.2.10 (Packet internet gropher)

To check LAN card status:


Ex: #ping 127.0.0.1

To check host name:


Ex: #hostname

Netstat: it will give network statistics (which port number of the server is connected to
which port number of client) Ex: #netstat ant

-a - > Show the state of all sockets and all routing table entries; normally, sockets used by server processes are not shown and only interface, host, network, and default routes are shown. -n -> Show network addresses as numbers. netstat normally displays addresses as symbols. This option may be used with any of the display formats. netstat Displays generic net statistics of the host you are currently connected to. netstat -an Shows all connections to the server including the source and destination ips and ports if you have proper permissions.

netstat -rn Displays routing table for all ips bound to the server.

netstat -an |grep:80 Display the amount of active connections on port 80.

nslookup
The name nslookup means "name server lookup".nslookup is a computer program used in Windows and Unix to query Domain Name System (DNS) servers to find DNS details, including IP addresses of a particular computer.

Using Command line:


unix% nslookup example.com Server: Address: 192.168.1.1 192.168.1.1#53

Non-authoritative answer: Name: example.com Address: 208.77.188.166

Using subcommands:
nslookup > server dns.com Default Server: dns.com Address: 169.254.82.215 > set type=mx > microsoft.com Server: dns.com Address: 64.40.103.249

microsoft.com MX preference = 0, mail exchanger = nullmx.domainmanager.com > exit

Uname

Print name of current system.

Print the name of the hardware implementation (platform).

Print the machine hardware name (class). Use of this option is discouraged; use
uname -p instead.

Print the nodename (the nodename is the name by which the system is known
to a communications network).

Traceroute
Print the route packets take to network host. When you connect to another computer, your traffic does not go directly to the machine you are attempting to connect to. Instead it goes through multiple machines on the internet known as routers. These machines serve the sole purpose of controlling how your traffic gets to your destination. If any one connection fails you will not be able to connect to the intended destination. There is a common utility known as traceroute, or tracert in DOS and Windows. The purpose of this utility is to show you the path your traffic takes when you are attempting to connect to another machine.

Remote Filesharing:
By using this remote file sharing we can send or get files from remote systems. 1) rsync 2) scp rsync stands for remote synchronization scp stands for secure copy

rsync:
Syntax: #rsync avz <source file> <destination IP> :< path> Ex: #rsync avz file1 192.168.2.15:/root Provide password

scp:
Syntax: #scp rv <source file> <destination IP> :< path> Ex: #scp rv file1 192.168.2.15:/root Provide password

Logging to the machine:


SSH: Secure Remote Login and Command Execution
ssh is used to connect into a remote machine and for executing commands on a remote host. Syntax: ssh user@hostname [command] Run a command on a remote host on which you have an account under the same user name: Ex: ssh 192.168.2.10 uptime Run a command on a remote host on which you have an account under a different user name: Ex: ssh 192.168.2.15 uptime

rlogin
To login to the remote system iona using the same username: Ex: rlogin iona Password: To login to the remote system barra using the username helper: rlogin barra -l helper Password: This logs the user in to the remote system named barra on which they have an account for the username helper. This username is different to their username on the system they are currently logged in to.

rsh
rsh executes command on the specified hostname. To do so, it must connect to a rshd service (or daemon) on the hostname machine.

When no user name is specified either with the -l option or as part of username@hostname, rsh connects as the user you are currently logged in as. If this is a domain user (that is, of the form domain\username), the whole name is sent. If you are not logged in as a domain user, the name machine_name\username) is sent. For example, if you logged in as the domain user mydomain\myname, the command Ex: $ rsh otherhost pwd

User commands
passwd - entering just passwd would allow you to change the password. After
entering passwd you will receive the following three prompts:

Each of these prompts must be entered and entered correctly for the password to be successfully changed.

Whoami- whoami outputs the username that the user is working under

Id: id - print real and effective UIDs and GIDs

finger :The finger displays information about the system users.

Finger may be used to look up users on a remote machine. The format is to specify a user as ``user@host '' or ``@host '' where the default output format for the former is the -l style, and the default output format for the latter is the -s style. The -l option is the only option that may be passed to a remote machine.

Last: Last searches back through the file /var/log/wtmp and displays a list of all users
logged in (and out) since that file was created. Names of users and tty's can be given, in which case last will show only those entries matching the arguments. Names of ttys can be abbreviated, thus last 0 is the same as last tty0.

Su:
Become super user or another user. Syntax su [ - ] [ username [ arg ] ] username arg Pass the environment along unchanged, as if the user actually logged in as the specified user. The name of another username that you wish to log in as. Additional arguments that need to be passed through the su command.

Manipulating files:
Sort: The Unix sort command is a command for the Unix family of operating systems.
It is designed to sort whatever information you give it.

sort

sort lines of a file (Warning: default delimiter is white space/character transition)

You can use the Linux sort command to sort all kinds of output from other commands. For instance, here's an example where I sort the output of the ls -al command: Example: sort -nr infile1 | more -n numeric sort -r reverse sort -k 3,5 start key
Example: $ ls -al | sort -n -k5

This results in the following output, which as you can see, is a directory listing, sorted by filesize (the 5th column):
-rw-r--r-total 992 -rw-r--r-drwxr-xr-x -rw-r--r-drwxr-xr-x 1 al 11 al 1 al 18 al al al al al 240 Feb 17 374 Jan 535 Feb 18 612 Feb 18 2010 files 2010 CreateAPodcast.out 2010 images 5 17:50 .. 1 al al 0 Feb 17 2010 CreateAPodcast.idx

drwxr-xr-x -rw-r--r--rw-r--r-drwxr-xr-x -rwxr-xr-x@ -rw-r--r--rw-r--r--@ copy -rw-r--r--rw-r--r--@ -rw-r--r--@ -rw-r--r--@

20 al 1 al 1 al 50 al 1 al 1 al 1 al 1 al 1 al 1 al 1 al

al al al al al al al al al al al

680 Feb 27 978 Feb 18 1425 Feb 18 1700 Feb 18 2716 Feb 18 4431 Feb 18 9689 Feb 17 13564 Feb 18 14369 Feb 18 14738 Feb 31 310657 Feb 18

2010 . 2010 CreateAPodcast.toc 2010 CreateAPodcast.lof 2010 CreateAPodcast 2010 CreateAPodcast.tex 2010 CreateAPodcast.aux 2010 CAPContent2.rga 2007 CreateAPodcast.log 2007 CAPContent2.tex 2007 CAPContent2.rga 2007 create-a-podcast-

The -n in my example means "sort numerically", and the -k5 option means to key off of column five. Like other Unix commands, these options can be combined and shortened, like this:

Sorting output of the ps command


From time to time you'll want to sort the output of the ps command, and again here, sort can be your friend. You can just sort alphabetically by the first column (username):
$ ps auxw | sort

Or you can sort numerically by column two (the PID field):


$ ps auxw | sort -nk2

You can also reverse that sort with the -r option:


$ ps auxw | sort -rnk2

Sorting file contents


You can also sort the contents of a file with the sort command. Here's what a file named files looks like before I sort it:
$ cat files 1-gb-startup.jpg

10-after-drum.jpg 2-use-for-buttons.jpg 3-after-media-button.jpg 4-after-loop-browser.jpg 5-after-jingles.jpg 6-after-male-voice.jpg 7-after-chipmunk.jpg 8-before-2nd-male-recording.jpg 9-after-2nd-male-recording.jpg

And here's the output when I run a simple sort command against it:
$ sort files 1-gb-startup.jpg 10-after-drum.jpg 2-use-for-buttons.jpg 3-after-media-button.jpg 4-after-loop-browser.jpg 5-after-jingles.jpg 6-after-male-voice.jpg 7-after-chipmunk.jpg 8-before-2nd-male-recording.jpg 9-after-2nd-male-recording.jpg

It's very important to note that this command does not sort the actual file, it just displays the sorted output on your terminal. To have the sorted output to another file, you'd run a command like this:
$ sort files > files.sorted

Which creates a new file named files.sorted, which contains the new, sorted output.

cut

cut is a Unix command line utility which is used to extract sections from each line of input usually from a file. Extraction of line segments can typically be done by bytes (-b), characters (-c), or fields (-f) separated by a delimiter (-d the tab character by default). A range must be provided in each case 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). Since version 6, an error is thrown if you include a zeroth value. Prior to this the value was ignored and assumed to be 1. OPTIONS: -f 2,4-6 -c 35-44 -d ':' Examples Assuming a file named file containing the lines:
foo:bar:baz:qux:quux one:two:three:four:five:six:seven alpha:beta:gamma:delta:epsilon:zeta:eta:teta:iota:kappa:lambda:mu

field character delimiter (default is a tab)

To output the fourth through tenth characters of each line:


% cut -c 4-10 file

This gives the output:


:bar:ba :two:th ha:beta

To output the fifth field through the end of the line of each line using the colon character as the field delimiter:
% cut -d : -f 5- file

This gives the output:


quux five:six:seven epsilon:zeta:eta:teta:iota:kappa:lambda:mu

wc

display a count of lines, words and characters in a file


wc [-c| -m| -C] [-lw]

[file...]

The wc utility reads one or more input files and, by default, writes the number of newline characters, words and bytes contained in each input file to the standard output. The utility also writes a total count for all named files, if more than one input file is specified. wc considers a word to be a non-zero-length string of characters delimited by white space (for example, SPACE, TAB).

OPTIONS
The following options are supported:
-c -m -C -l -w

Count bytes. Count characters. Same as -m. Count lines.

Count words delimited by white space characters or new line characters. Delimiting characters are Extended Unix Code (EUC) characters from any code set defined by iswspace(). If no option is specified the default is -lwc (count lines, words, and bytes.)

Examples:
who | wc -l

counts the number of users logged


ps -e | wc -l

counts the number of processes


ls -l | grep ^d | wc -l # finds the number of subdirectories in the current

directory.
wc -l /etc/passwd

tells you the number of lines (accounts) in the /etc/passwd file.


wc -w readme.txt

Counts the number of words in the file named readme.txt

paste
Merge lines of files Example: paste infile1 infile2 > outfile2

Examople: $ cat f1.txt a b c $ cat f2.txt 1 2 Now:

$ paste f1.txt f2.txt a 1 b 2

$ paste f2.txt f1.txt 1 a 2 b c

Using -d (delimiter) and -s (serial) options: $ paste -s -d : f1.txt f2.txt a:b:c 1:2 Now some additional examples: Example 1: We can specify a delimiters list instead of a single delimiter with -d option. Suppose you have 3 files fa.txt, fb.txt and fc.txt.
$ cat fa.txt 20 60 90 12 $ cat fb.txt 60 90 12 14 $ cat fc.txt 70 90 80 12

Required: The requirement is to add the individual lines from fa.txt with fb.txt and then subtracting the corresponding line from fc.txt. Lets construct the expression first:
$ paste -d"+-" fa.txt fb.txt fc.txt 20+60-70

60+90-90 90+12-80 12+14-12

Then use bc to evaluate each line of expression like this:


$ paste -d"+-" fa.txt fb.txt fc.txt| while read line do echo -n "($line)=" echo $line | bc done Output: (20+60-70)=10 (60+90-90)=60 (90+12-80)=22 (12+14-12)=14

cat

concatenate files together Example: cat infile1 infile2 > outfile2 -n -vet number lines show non-printing characters (good for finding problems)

cat file2 >> file1 appends contents of file2 to file1 cat file1 file2 > file3 concatenates file1 and file2, and writes the results in file3.

The following command: cat -n myfile

writes the contents of the file myfile to standard output with each line numbered.

uniq remove duplicate lines (normally from a sorted file)


Example: sort infile1 | uniq -c > outfile2 -c -d show count of lines only show duplicate lines

cmp compare two files


The cmp utility compares two files of any type and writes the results to the standard output. By default, cmp is silent if the files are the same; if they differ, the byte and line number at which the first difference occurred is reported. Bytes and lines are numbered beginning with one. The following options are available:
-l

Print the byte number (decimal) and the differing byte values (octal) for each difference.
-s

Print nothing for differing files; return exit status only. The optional arguments skip1 and skip2 are the byte offsets from the beginning of file1 and file2 respectively, where the comparison will begin. The offset is decimal by default,

but may be expressed as an hexadecimal or octal value by preceding it with a leading ``0x'' or ``0''. The cmp utility exits with one of the following values:
0 1

The files are identical.

The files are different; this includes the case where one file is identical to the first part of the other. In the latter case, if the -s option has not been specified, cmp writes to standard output that EOF was reached in the shorter file (before any differences were found). An error occurred. Example: cmp infile1 infile2
>1

diff

compare 2 or 3 files - show differences Example: diff infile1 infile2 | more Example: diff3 infile1 infile2 infile3 > outfile1

If you need to compare two text files in Unix, you're mostly likely to use the diff command. Suppose you have two files in /tmp directory: /tmp/1.txt:
aaa bbb ccc ddd eee fff ggg

and /tmp/2.txt:
bbb c c ddd eee fff ggg hhh

I have deliberately created them so short and simple this way it's easier to explain how the comparison works. If there are no differences between the files, you will see no output, but if two text files are indeed different, all the text mismatches will be highlighted using the standard diff output:
$ diff /tmp/1.txt /tmp/2.txt 1d0 < aaa 3c2 < ccc --> c c 7a7 > hhh

Lines like "1d0" and "3c2" are the coordinates and types of the differences between the two compared files, while lines like "< aaa" and "> hhh" are the differences themselves. Diff change notation includes 2 numbers and a character between them. Characters tell you what kind of change was discovered: d a line was deleted c a line was changed a a line was added

Number to the left of the character gives you the line number in the original (first) file, and the number to the right of the character tells you the line number in the second file used in comparison. So, looking at the two text files and the diff output above, you can see what happened: This means that 1 line was deleted. < aaa suggests that the aaa line is present only in the original file:
1d0 < aaa

And this means that the line number 3 has changed. You can see how this confirms that in the first file the line was "ccc", and in the second it now is "c c".
3c2 < ccc --> c c

Finally, this confirms that one new line appeared in the second file, it's "hhh" in the line number 7:
7a7 > hhh

Job related commands


Jobs:
Lists the jobs that you are running in the background and in the foreground. If the prompt is returned with no information no jobs are present. Syntax jobs [-p | -l] [-n] [-p] [-x] [job id] -p | -l -n -p Report the process group ID and working directory of the jobs. Display only jobs that have stopped or exited since last notified. Displays only the process IDs for the process group leaders of the selected jobs.

-x

Replace any job_id found in command or arguments with the corresponding process group ID, and then execute command passing it arguments. The job id.

job id

bg:
Continues a stopped job in the background. This function is not available on all Unix shell's. Syntax bg [-l] [-p] [-x] [job] -l -p -x Report the process group ID and working directory of the jobs. Report only the process group ID of the jobs. Replace any job_id found in command or arguments with the corresponding process group ID, and then execute command passing it arguments. Specifies the job that you want to run in the background.

job

Examples bg - Lists the current running jobs.

fg:
Continues a stopped job by running it in the foreground, some shells are not able to run this command. Syntax fg [%job] %job Examples fg - Typing fg alone will resume the first job were it was left off. fg 1 - specifying the job (in this case 1) will resume that particular job. The job id can be determined by running the bg command. Specifies the job that you want to run in the foreground.

File archiving commands


Tar:
Create tape archives and add or extract files. #tar <options> <destination> <source> Note: destination must be in .tar extension Options: -c=create -v=verbose -f=file -t=table of content

-x=extract to -w=interactive -z=zip To take backup Syntax: #tar -cvf <path> <file name> <source> Ex: tar -cvf passwd.tar /etc/passwd To list the content of tar file #tar -tvf <path> <file name> Ex: tar -tvf passwd.tar To extract content of file #tar -xvf <path> <file name> Ex: tar -xvf passwd.tar To take backup along with zip #tar -cvzf <path> <file name> Note: file name must be with an extension of .tar.gz Ex: tar -cvzf passwd.tar.gz /etc/passwd To extract zip file #tar -xvzf <path> <file name> Ex: tar -xvzf passwd.tar.gz

Jar:
The jar tool combines multiple files into a single JAR archive file. jar is a generalpurpose archiving and compression tool, based on ZIP and the ZLIB compression format. However, jar was designed mainly to facilitate the packaging of java applets or applications into a single archive. When the components of an applet or application (.class files, images and sounds) are combined into a single archive, they may be downloaded by a java agent (like a browser) in a single HTTP transaction, rather than requiring a new connection for each piece. This dramatically improves download times. jar also compresses files and so further improves download time. Typical usage to combine files into a jar file is: % jar cf myFile.jar *.class In this example, all the class files in the current directory are placed into the file named "myFile.jar". A manifest file entry named META-INF/MANIFEST.MF is automatically generated by the jar tool and is always the first entry in the jar file. The manifest file is the place where any meta-information about the archive is stored as name: value pairs.

If you have a pre-existing manifest file whose name: value pairs you want the jar tool to include for the new jar archive, you can specify it using the m option: % jar cmf myManifestFile myFile.jar *.class To extract the files from a jar file, use x, as in: % jar xf myFile.jar To extract only certain files from a jar file, supply their filenames: % jar xf myFile.jar foo bar

Finding things
find:
The find program is a directory search utility on Unix-like platforms. It searches through one or more directory trees of a filesystem. The find command allows the Unix user to process a set of files and/or directories in a file subtree. You can specify the following:

where to search (pathname) what type of file to search for (-type: directories, data files, links) how to process the files (-exec: run a process against a selected file) the name of the file(s) (-name) perform logical operations on selections (-o and -a)

Search for file with a specific name in a set of files (-name)

This command will search in the current directory and all sub directories for a file named file1. Note: The -print option will print out the path of any file that is found with that name. In general -print will print out the path of any file that meets the find criteria.

How to search for a string in a selection of files (-exec grep ...).


find . -exec grep "www.athabasca" '{}' \; -print This command will search in the current directory and all sub directories. All files that contain the string will have their path printed to standard output. If you want to just find each file then pass it on for processing use the -q grep option. This finds the first occurrance of the search string. It then signals success to find and find continues searching for more files. find . -exec grep -q "www.athabasca" '{}' \; -print

This command will search for a string in all files from the /tmp directory and below:
find /tmp -exec grep "search string" '{}' /dev/null \; -print

The /dev/null argument is used to show the name of the file before the text that is found. Without it, only the text found is printed. An equivalent mechanism is to use the "H" or "--with-filename" option to grep:
find /tmp -exec grep -H "search string" '{}' \; -print

Example of search for "LOG" in jsmith's home directory


find ~jsmith -exec grep "LOG" '{}' /dev/null \; -print

Example of search for the string "ERROR" in all xml files in the current directory and all sub-directories
find . -name "*.xml" -exec grep "ERROR" '{}' \; -print

The double quotes (" ") surrounding the search string and single quotes (' ') surrounding the braces are optional in this example, but needed to allow spaces and other special characters in the string. This command is very important for process a series of files that contain a specific string. You can then process each file appropriately.

This find example searches through the root filesystem ("/") for the file named "Chapter1". If it finds the file, it prints the location to the screen. find / -name Chapter1 -type f -print A nice thing to know is that on Linux systems and modern Unix system you no longer need the -print option at the end of the find command, so you can issue it like this: find / -name Chapter1 -type f This next find command searches through the /usr and /home directories for the file named Chapter1: find /usr /home -name Chapter1 -type f To search in the current directory, and all subdirectories, just use the . character to reference the current directory in your find commands, like this: find . -name Chapter1 -type f This next command searches through the /usr directory for all files that begin with the letters Chapter, followed by anything else. The filename can end with any other combination of characters. It will match filenames such as Chapter, Chapter1, Chapter1.bad, Chapter-in-life, etc.: find /usr -name "Chapter*" -type f This next command searches through the /usr/local directory for files that end with the extension .html. These file locations are then printed to the screen.

find /usr/local -name "*.html" -type f -print

Search in case insensitive mode


find . -iname "MyFile*"

If the -iname switch is not supported on your system then workaround techniques may be possible such as: find . -name "[mM][yY][fF][iI][lL][eE]*" This uses Perl to build the above command for you:
echo "'MyFile*'" |perl -pe 's/([a-zA-Z])/[\L\1\U\1]/g;s/(.*)/find . -name \1/'|sh

Search files by size


Example of searching files with size between 100 kilobytes and 500 kilobytes. find . -size +100k -a -size -500k The units should be one of [bckw], 'b' means 512-byte blocks, 'c' means byte, 'k' means kilobytes and 'w' means 2-byte words.

How to find directories with find


Every option you just saw for working with files can also be used on directories. Just replace the -f option with a -d option. For instance, to find all directories named build under the current directory, use this command: find . -type d -name build

Finding files that contain text (find plus grep)

You can combine the find and grep commands to powerfully search for text strings in many files. This next command shows how to find all files beneath the current directory that end with the extension .java, and contain the characters StringBuffer. The -l argument to the grep command tells it to just print the name of the file where a match is found, instead of printing all the matches themselves:
find . -type f -name "*.java" -exec grep -l StringBuffer {} \;

(Those last few characters are required any time you want to exec a command on the files that are found. I find it helpful to think of them as a placeholder for each file that is found.) find / -name core | xargs /bin/rm -f This command will efficiently remove all files named core from your system This next example is similar, but here I use the -i argument to the grep command, telling it to ignore the case of the characters string, so it will find files that contain string, String, STRING, etc.: find . -type f -name "*.java" -exec grep -il string {} \;

which:
Tell which version of a program or command will be used in your session in case of multiple copies; e.g. #which cc /usr/bin/cc

Whereis:
Locates source for program or command Ex: #whereis cc cc: /usr/bin/cc fuser -u <filename>

- show who is using a file.(system hogging command). Useful when trying to work out who has locked a row or table in an informix database for example.

. Executing a background job


Appending an ampersand ( & ) to the command runs the job in the background. For example, when you execute a find command that might take a lot time to execute, you can put it in the background as shown below. Following example finds all the files under root file system that changed within the last 24 hours.
# find / -ctime -1 > /tmp/changed-file-list.txt &

2. Sending the current foreground job to the background using CTRL-Z and bg command
You can send an already running foreground job to background as explained below:

Press CTRL+Z which will suspend the current foreground job. Execute bg to make that command to execute in background.

For example, if youve forgot to execute a job in a background, you dont need to kill the current job and start a new background job. Instead, suspend the current job and put it in the background as shown below.
# find / -ctime -1 > /tmp/changed-file-list.txt # [CTRL-Z] [2]+ Stopped list.txt # bg find / -ctime -1 > /tmp/changed-file-

3. View all the background jobs using jobs command


You can list out the background jobs with the command jobs. Sample output of jobs command is
# jobs [1] Running [2]- Running [3]+ Done bash download-file.sh & evolution & nautilus .

4. Taking a job from the background to the foreground using fg command


You can bring a background job to the foreground using fg command. When executed without arguments, it will take the most recent background job to the foreground.

# fg

If you have multiple background ground jobs, and would want to bring a certain job to the foreground, execute jobs command which will show the job id and command. In the following example, fg %1 will bring the job#1 (i.e download-file.sh) to the foreground.
# jobs [1] Running [2]- Running [3]+ Done # fg %1 bash download-file.sh & evolution & nautilus .

5. Kill a specific background job using kill %


If you want to kill a specific background job use, kill %job-number. For example, to kill the job 2 use
# kill %2

To kill a foreground jobs, use one of the methods specified in our earlier article 4 Ways to Kill a Process kill, killall, pkill, xkill.

Das könnte Ihnen auch gefallen