unix basic commands
DESCRIPTION
unix basic commandsTRANSCRIPT
Unix Basic Comands
Unix Basic Comands
Ericsson Internal
Prepared (also subject responsible if other)No.
ETR/R/BUR Bogdan Iordache
ApprovedCheckedDateRevReference
DOCPROPERTY "ApprovedBy" \* MERGEFORMAT DOCPROPERTY "Checked" \* MERGEFORMAT 5 Sept 2007 DOCPROPERTY "Reference" \* MERGEFORMAT
1. Getting help in UNIX
1.1. Manual pages: man commandSyntax: man commandwhere command is the command the user wants to look up.
Manual pages are the quickest and easiest source for complete information on how to use the commands on your system. They provide information on what programs do and how to use them. ex.1: $ man ls
1.2. Manual pages: whatis commandSyntax: whatis commandWhatis command is similar with man command and is used when the user just want to see a subset of the information on a man page.
The man command used with the f switch is similar to the whatis command.
By using whatis or man -f followed by a command name, you will get a description summary of that command. For example, to print a description summary for the date command, type the following, and a short description of what date does will be returned.
ex.1: $ whatis date
2. Navigating the file system
2.1. Displaying your working directory: pwd command
Syntax: pwd The pwd command is used to find out which is the current working directory.
ex. 1: Recall the directory structure from Unix file-system. Lets say that that we are currently in work directory. Typing :
$ pwd
Will display the absolute path to the root:
/home/will/work
2.2. Listing directories: ls command
Syntax: ls [option] directoryls lists the contents of a directory. If no target directory is given, then the contents of the current working directory are displayed. So, if the current working directory is / (root directory), and we have a folders diagram looking like this:
Fig. 1 UNIX file-system
Then the command :$ ls
will output this:
bin sbin home tmp lib usr var
Actually, ls doesn't show you all the entries in a directory. Files and directories that begin with a dot (.) are hidden (this includes the directories '.' and '..' which are always present). The reason for this is that files that begin with a `.` usually contain important configuration information and should not be changed under normal circumstances. If you want to see all files, ls supports the -a option:
$ ls -a
Even this listing is not that helpful because there are no hints to properties such as the size, type and ownership of files, just their names. To see more detailed information, use the -l option (long listing), which can be combined with the -a option as follows:
$ ls -a -l or, equivalently $ ls -al
2.3. Changing directory: cd command
Syntax: cd pathex.1: $ cd /home/willchanges your current working directory to /home/will (which can be an absolute or a relative path). One of the most common relative paths to use is '..' (i.e. the parent directory of the current directory). So, if your current directory is 'will' (see diagram above) and you type $ cd .. it will move you to the parent directory of 'will' that is the 'home' directory.
Also, lets say that you want to move from 'will' to 'work', then you simple type:
$ cd work
because the `work` directory is included into `will`, but if you want to move to another directory not included into 'will', like 'bin', then youll have to return to the root ('/'), and the command will be this:
$ cd /usr/bin.
Used without any target directory
$ cd
resets your current working directory to your home directory (useful if you get lost). Same thing with:
$ cd ~
(it doesnt matter where you are)
If you change into a directory and you subsequently want to return to your original directory, use
$ cd -
3. Viewing contents of a file
3.1. Displaying the type of a file: file command Syntax: file filenamefile analyzes a file's contents for you and reports a high-level description of what type of file it appears to be: ex. 1: $ file myprog.c letter.txt webpage.html The output will eventually appear as:
myprog.c: C program text letter.txt: English text webpage.html: HTML document text
3.2. Concatenating and displaying a file: cat command
Syntax: $ cat filenameDisplays the contents of filenameon the screen, one after the other. You can also use it to create files from keyboard input using the > operator, as follows:
ex.1: $ cat > hello.txt hello world! [ctrl-d] (to stop)ex.2: $ cat hello.txt The output will be: hello world! What weve done is that we created a text file named hello.txt with hello world! inside and then weve displayed it.
3.3. Displaying the content of a file: more command
Syntax: $ more filenameViewing pages one at a time is done with the concept of pagers. Files that scroll off the screen will be useless if you need to read the beginning of the file. If the file's size is larger than what can fit on the terminal screen or in your history buffer, you cant see all the content . Files are often large enough to do this, and you will still want to read those files.You can use more, less , head, tail commands. More is a filter for paging through text one full screen at a time. This version is especially primitive. Users should realize that less provides more emulation and extensive enhancements. ex 1: $ man file1
The output will be (that text is an example):
asdas
Asdsafs
Df
Fd
ddd
dfd
g
--More--(53%)
Fifty-three percent is what you have seen and the rest is what still needs to be seen. You know from the percentage how many pages you are dealing with. If you had 25%, then it's three or four pages of output to view.Pressing Enter will bring one line at a time . Pressing the Spacebar will bring you to the next page. You can use the q on the keyboard to quit the program, or Ctrl+z will also stop the more command if you want to break the sequence of using it. Using s on the keyboard will skip one line at a time and is helpful to use if you want to scroll through your output line by line, instead of page by page.
ex2 : $ man s file1
The output will be (that text is an example):
asdas
Asdsafs
Df
Fd
ddd
dfd
g
k
--More--(53%)
Using the -s option we are able to view multiple blank lines squeezed together into one.
3.4. Displaying the content of a file: less command
Syntax: $ less filename
Using the less command is similar to using the cat and more commands. As a matter of fact, the syntax is nearly identical. It's really what the tool does that makes it different. When using the less command, you have more control over the pager than ever before. If you try to use the arrow keys for navigation while using the more command, you will find that you can only move forward through the file with the Spacebar. There is not a back and forth as there is with the less command. You can move up and down through the file using your arrow keys. You can even move to the right buffer if you are working on a terminal emulation program like telnet or secure shell. Other options that come with less are similar to those that come with cat and more. The Spacebar always moves you through the file via the page, and q will give you the ability to quit out of the program. Here are some keys used for navigation: Arrows/PageUp/P.Down/Home/End keys: Navigation ; Space bar: Page down ; b: Page up ; ng: Jump to line number n ; h : help , q: Quit ex1 : $ less file2
The output will be (that text is an example):
asdf
Asf
Saf
file2
The user can navigate according to the special keys.3.5. Displaying the first lines of a file: head command
Syntax: $ head filenameYou may have a need to look at the bottom of a log file, or at the top of an email message header to get the source and destination addressing out of it. If you do not need to look at a complete file and just need to look at a section of it, then you can use the head and tail commands. In order to see the first lines from the content of file you use the head command . The output of this command starts from the top and displays (by default) 10 lines from the top down . The user can choose how many lines he wants to view by placing the number of lines into the options field. ex1: $ head file
The output will be:
line1
.
.
line10
ex2: $ head -3 file (or $ head -3 file)
The output will be:
line1
line2
line3
This command will display only the first three lines of the file.
3.6. Displaying the last lines of a file: tail command
Syntax: $ tail filenameIn order to see the last lines from the content of file you use the tail command . The output of this command starts from the bottom and displays (by default) 10 lines from the bottom up . The user can choose how many lines he wants to view by placing the number of lines into the options field.
This command is the opposite of the head command.
ex1: $ tail file
The output will be:
line (n-9)
.
.
last line (n)
ex2: $ tail -3 file (or $ tail -3 file)
The output will be:
line (n-2)
line (n-1)
last line (n)
This command will display only the last three lines of the file.
4. Finding files
4.1. Finding files : find command
Syntax: find-path-name-list expressions Find recursively descends the directory hierarchy for each pathname in the pathname list (i.e., one or more pathnames) seeking files that match options. First argument is the path where the search starts. The rest of the arguments specify some criteria by which to find the files, such as name, size, owner, permissions, etc..
ex1: $ find . -name \*.c -print
Starting at the present working directory (dot), finds all files ending in .c and prints the full pathname of the file.
ex2: $ find .. -type f -printStarting at the parent directory (dot dot), finds all files of type file; i.e., files that are not directoriesex3: $ find / -size 0 - exec rm "{}" \;
Starting at the root directory, finds all files of size zero and removes them. The {} are used as a place holder for the name of each file as it is found.4.2. Finding pattern : grep command
Syntax: grep [-options] pattern [file]
Grep searches line-by-line for a specified pattern, and outputs any line that matches the pattern. If the file argument is omitted, grep will read from standard input. It is always best to enclose the pattern within single quotes, to prevent the shell from misinterpreting the command.ex1: $ grep 'hello' /home/bogdan/fileSearches the /home/bogdan/file file for any lines containing the string hello.From the options that may be included, there are a few to be noticed-c (print a count of the number of lines that match)
-i (ignore case)
-v (print out the lines that don't match the pattern)
-n (printout the line number before printing the matching line).ex2: $ grep v i 'hello' /home/bogdan/fileSearches the /home/bogdan/file for any lines not containing the string hello, HELLO, Hello or any other combination .The grep utility recognizes a variety of patterns, and the pattern specification syntax was taken from the vi editor. Here are some of the characters you can use to build grep expressions:
The caret (^) matches the beginning of a line. The dollar sign ($) matches the end of a line. The period (.) matches any single character. The asterisk (*) matches zero or more occurrences of the previous character (also known as wildcard). The expression [a-b] matches any characters that are lexically between a and b.
So,
[0-3] is the same as [0123] [a-k] is the same as [abcdefghijk][A-C] is the same as [ABC][A-Ca-k] is the same as [ABCabcdefghijk]
There are also some alternate forms :
[[:alpha:]] is the same as [a-zA-Z][[:upper:]] is the same as [A-Z][[:lower:]] is the same as [a-z][[:digit:]] is the same as [0-9][[:alnum:]] is the same as [0-9a-zA-Z][[:space:]] matches any white space including tabs
Lets say we have a file called file1. That is
$ cat file1
1a3 hello
hello world
helo
helllo
hello.world
says Daniel Fletcher
or Dan Fletcher
or Dan Thomas
The command
ex3: $ grep [[:digit:]].*[[:digit:]] file1will print out the first line.
If we want to print out the line ended with hello followed only by a possible white space, we type
ex4: $ grep hello[[:space:]]*$ file1Another important concept to be introduced is the concept of an "escaped" character.
An escaped character is a character preceded by a backslash. The preceding backslash does one of the following:(a) removes an implied special meaning from a character(b) adds special meaning to a "non-special" character Lets say we want to print out the line containing hello.world. If we type the line with hello world will be displayed also, as the dot . matches any character, including the white space. But if we put the \ sign in front of the dot, the shell will interpret literally the dot, so the character will be escaped. So the correct typing for this example is:
ex.5: $ grep hello\.world file1Another important concept is that an expression consisting of a character followed by an escaped question mark matches one or zero instances of that character. So lets say we want to select the lines containing the hello and helo words, but not helllo. The correct command is
ex.6. $ grep hell\?o from file1We move on to "grouping" expressions. In our example, we want to make the string "iel" following "Dan" optional, so that we select the line including Daniel Flecher, but Dan Fletcher too.
An expression surrounded by "escaped" parentheses is treated as a single character. So the correct command for this is:
ex.7 $ grep Dan\(iel\)\? Fletcher file1Now lets consider we want to select the lines containing the word Fletcher or the word Thomas. In this case well use the or \| operator:
ex.8 $ grep Fletcher \| Thomas file14.3. ds
4.4. sfs5. File and directory permission
5.1. Setting permissions of a file: chmod commandSyntax: chmod mode fileTo set file permissions, you may use to the "rwx" notation to specify the type of permissions, and the "ugo" notation to specify those the permissions apply to.rwx" - read ,write, execute
ugo - user(owner of the file), group(same group as the owner), other
To define the kind of change you want to make to the permissions, use the plus sign (+) to add a
permission, the minus sign (-) to remove a permission, and the equal sign (=) to set a permission
directly.
ex1: $ chmod g=rw ~/test.txt
To change the file permissions on the file test.txt, in your home directory. Specifically, you are
specifying group read access and write access, with no execute access.
ex2: $ chmod u=rwx,go=r-x ~/test.txtYou can also combine multiple operation codes in a single statement. The example above will set
owner permissions to rwx, with group and other permissions set to r-x.
6. Creating directories and links
6.1. Creating a directorySyntax: mkdir directoryThe Unix mkdir command is used to make directories. If you do not specify the place where you want the directory created (by giving a path as part of the directory name), the shell assumes that you want the new directory placed within the current working directory.
ex1: $ mkdir ~/testThis will create a directory called test within your home directory. ex2: $ mkdir ~/test/documents
Create a directory called documents, within the directory called test, within your home directory. Alternately, you could type: $ cd ~/test; mkdir documents6.2. Creating a link
Syntax: ln filename linknameCreates a hard link between to files or a file and a directory.ex1: $ ln file1 file2
This links file2 to file1 of the same file system. File2 is practically a replica of file1, containing the same information and having the same size. When modifying one file, the other one is modified to (so this makes the big difference from just copying file1 into file2). When deleting one of the two linked files, the other one remains as an independent file.
ex2: $ ln /home/mihai/webpage/index.html /home/bogdan/binThis links file index.html from Mihais webpage directory to the Bogdans bin directory. It may used to link files from other users accounts. Not all UNIX systems support this kind of file-directory link
Syntax: ln -s filename linknameCreates a soft or symbolic link between two files. This feature does not copy the source file in a replica, but creates a logical connection which occupies a smaller disk size than the source. When accessed, the link offers all the information of the source. When deleting the source, the link remains, but accessing it brings no info anymore (as it links to nothing).
7. File hanling commands7.1. Removing files: rm commandSyntax: rm fileThe rm command is used to delete unwanted files on your Unix system. You can delete multiple files by leaving a space after each filename and then specifying the next. You can add or remove multiple files by specifying what files you want to add or remove, one after the other in tandem.
ex.1: $ rm hello.txt
This command will delete the unwanted file hello.txt from the current working directory.
After issuing the rm command for the file(s) you want to delete, you might be presented with a response such as
remove hello.txt (y/n)?
The rm command supports several useful options such as i, -f, and r. Each option will perform a different function when specified.
The "i" stands for interactive mode. The -i option makes rm ask you to confirm the deletion of each file before it is actually deleted.
7.2. Removing directories: rmdir commandSyntax: rmdir directoryThe rmdir command will delete an empty directory. What this means is that the directory you want to remove cannot contain any data within it.
ex.1: $ rmdir jane
This command will delete the empty directory jane.7.3. Copying files: cp command
Syntax: cp sourcefile destinationfile The cp command is used when you want to make a copy of a file(s). The cp command will allow you to copy a single file to a new destination file, or copy one or more files to a single destination directory.
ex. 1: Make a copy of file hello.txt from work directory (lets imagine that you are in work directory) into play directory with the same name.
$ cp hello.txt ../playThe cp command has a recursive mode for copying directories. When it is used with the following syntax, the cp command with the -r option, you will be able to copy each source directory (as well as files) into whatever destination directory you specify. An example of this would be as follows:
$ cp -r [...] .ex. 2: copy jane directory into will directory (you are in home directory)$ cp r ./jane ./will7.4. Moving files: mv command
Syntax: mv sourcefile directoryWhen you want to move a file or directory, you need to use the mv command. The mv command will move or rename a file based on the destination.
ex. 1: $ mv ./will/play/hello.txt ./janeThis command will move the file hello.txt from play directory into jane directory (considering you are in home directory). 8. Text processing command
8.1. The word count command
Syntax : wc [option] fileIn sum, the wc command counts words and provides you with a summary of what is found. Unix will report to you how many words are in a particular file. The wc stands for word count. When you want to see how many words are typed in a file, you simply need to execute the command and then the filename with its absolute or relative path. You will be shown the word count as well as the number of bytes, words, and lines in files.
To use wc, simply supply the name of a file you want analyzed in the following form: wc . If you pass more than one filename to wc, all the files are processed, and a grand total for everything is returned.
ex1: $ wc /var/log/boot.msg
340 225 20102 /var/log/boot.msg8.2. Sorting the content of a file : sort command
Sorts the lines in a text file.
Syntax : sort [option ] filename
-bIgnores spaces at beginning of the line.
-dUses dictionary sort order and ignores the punctuation.
-fIgnores caps
-iIgnores nonprinting control characters.
-mMerges two or more input files into one sorted output.
-MTreats the first three letters in the line as a month (such as may.)
-nSorts by the beginning of the number at the beginning of the line.
-rSorts in reverse order
-uIf line is duplicated only display once
+fieldsSorts by fields , usually by tabs
filenameThe name of the file that needs to be sorted.
-o outputfileSends the sorted output to a file.
ex1: sort -r file.txt
Would sort the file file.txt in reverse order
9. Manipulating processes and jobs9.1. Process status
Syntax: psTo find out the process ID of the underlying processes associated with the shell use ps (process show):
ex.1: $ ps
PID TTY TIME CMD 17717 pts/10 00:00:00 bash 27501 pts/10 00:00:01 find 27502 pts/10 00:00:00 ps
So here the PID of the shell (bash) is 17717, the PID of find is 27501 and the PID of ps is 27502.
9.2. Listing current jobs
Syntax: 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. Note: not all shells are capable of running this command.
ex1: $ jobs
[1]+ Stopped (user) man jobsAs you can see in the above job example the id is 1, it has been stopped by the user and the process in this case is man jobs (looking at the manual for jobs).
9.3. Terminating a process
Syntax: kill %job number kill PIDTo terminate a process or job abrubtly, use the kill command. It can be used in two ways - by their PID or by their job number.
ex1:$ kill %1 or $ kill 27501 This would terminate the find process listed in the ps example above . Actually kill only sends the process a signal requesting its shutdown and exit gracefully (the SIGTERM signal), so this may not always work. To force a process to terminate abruptly (and with a higher probability of sucess), use a -9 option (the SIGKILL signal):
ex2: $ kill -9 27501
Kill can be used to send many other types of signals to running processes. For example a -19 option (SIGSTOP) will suspend a running process. To see a list of such signals, run kill -l.
9.4. Move a suspended process to the background: bg commandSyntax: bg [%job]Unix lets you run more than one process at a time. Remember with Unix, every command or program that you use is considered a process. Many times you will want something to run on your Unix system but you won't want to see or use it while it is running. Having this process in the foreground will only cause you to waste time watching something that could be taking place without your input. In this situation, you would want to run a background process. Whereas a foreground process remains in the foreground and usually takes up many of the resources available on your system, a background process can run largely without your intervention.
Making a command run in the background is simple; you simply add an ampersand (&) to the end of the line containing the command. In Unix, you can stop any process that is running by pressing Ctrl+z. This stops the foreground process. To turn any process into a background process, first press Ctrl+z to suspend the process if it is running and you did not enter an ampersand following the command.Consider the following example: pressing Ctrl+z will output:
[10]+ Stopped at 2
Where at 2 is the command which is executing commands once at a single specified time . Here, the at command has been suspended and assigned job number 10.
* The process ID (PID) (as shown with the ps command) is a number used by the kernel to keep track of every process running on the system. This is not the same as the job number. The job number will identify the process number locally in your session, not globally to the system.
ex 1: $ bg %10
This command moves the stopped process to the background. After bg the user has to add the job number directly behind it. This command is usefull if you want to run multiple jobs while still being able to control and work with UNIX.9.5. Bring back a process from background to foreground: fg commandSyntax: fg [%job]
Just as you can send processes to the background, you can also bring them back to the foreground. This is done by using the foreground (fg) command. In the previous example a process was put to background and if you want to bring back the at command to foreground, you would simply enter the following:ex.1: $ fg %10
With the fg command, you can quickly bring the process you want to work on to the foreground. When you are done working with this process, you can send it back again with the bg command.10. Redirecting input/outputA program can be told where to look for input and where to send output, using input/output redirection. Unix uses the "less than" and "greater than" special characters (< and >) to signify input and output redirection, respectively.
10.1. Redirecting input
Syntax: < fileUsing the "less-than" sign with a file name in a shell command instructs the shell to read input from a file called "file" instead of from the keyboard. ex.1: $ more < /etc/passwd
Sends the contents of the file /etc/passwd to the more.
ex.2: $ head < /etc/passwdSee the first ten lines of the /etc/passwd file, the command:
10.2. Redirecting output
Syntax: > file
Using the "greater-than" sign with a file name causes the shell to place the output from the command in a file called "file" instead of on the screen.ex.1: $ ls /tmp > ~/ls.outRedirects the output of the ls command into a file called "ls.out" in your home directory. Remember that the tilde (~) is Unix shorthand for your home directory. In this command, the ls command will list the contents of the /tmp directory.
ex.2: $ ls /tmp > myls
$ ls /etc >> mylsUse two "greater-than" signs to append to an existing file. For example: >> file2 causes the shell to append the output from a command to the end of a file called "file2". If the file "file2" does not already exist, it will be created.
In example 2, it list the contents of the /tmp directory, and put it in a file called myls. Then, I list the contents of the /etc directory, and append it to the file myls.11. Pipelines
Unix commands alone are powerful, but when you combine them together, you can accomplish complex tasks with ease. The way you combine Unix commands is through using pipes. To create a pipe in Unix, you simply use a | character between the programs on the command line. A pipe is created by using the keystroke Shift+\. This creates a pipe, which looks like this: |. The pipe, used at the shell prompt, will also help manipulate input.
ex1: $ cat newfile1.txt Hello
How are you
Fine
$ cat newfile1.txt | wc
1 3 1
The word count command (wc) was used with cat and that's what the pipe is good at. Instead of being able to change output from one direction to another based on a file, you can now do the same with commands. This essentially is your primer for joining Unix commands together to unleash even more power under the hood.
We can also pipe into pagers. We learned about pagers earlier in this book. Piping things into pagers is common when you want to view a long listing and do not want it to run off the screen. This was another commonly used MS-DOS command. In Unix, simply type
ex2: $ ls -l | moreThis looks at your current directory listing, and if it is too long, you can use the more command in conjunction with the ls command to stop the listing at a page. Then you need to press Enter or your spacebar to cycle through the listing. Ctrl+z can break the list if it appears to go on forever.
12. Variables and built-in arithmetic
12.1. Variables
Syntax: variable=valueFor example, to assign the value 1 to the shell variable count, you simply write
$ count=1
and to assign the value /users/bogdan/work to the shell variable folder, you simply write
$ folder=/home/bogdan/workThe $ character is a special character to the shell. If a valid variable name follows the $, the shell takes this as an indication that the value stored inside that variable is to be substituted at that point. So, when you type
$ echo $count
the shell replaces $count with the value stored there; then it executes the echo command:
1
In the same manner, when typing
$ ls $folderthe shell will output the content of /home/bogdan/work
The variable could be also the name of a command. For example, lets consider the file employees containing the following entries: steve, george, jessica.
Typing at the shell:
$ command1=wc$ command2=-l$ command3=employees$ $command1 $command2 $command3will output
3 employees
12.2. Built-in arithmetic logic
Syntax: $((expression))
where expression is an arithmetic expression using shell variables and operators.
ex1: $ echo $((j+3))adds three to the value in the shell variable j and prints the result. In this case, the variable j doesn't have to be preceded by a dollar sign. That's because the shell knows that the only valid items that can appear in arithmetic expansions are operators, numbers, and variables. If the variable is not defined or contains a NULL string, its value is assumed to be zero. So, the printed output will be:
3
The assignment may be used before the arithmetic expansion. So, to add to the variable j the value 3 and assign the result back to j you can write$ j=$(( j+ 3 ))
To test whether j is greater than or equal to -5 and less than or equal to 10, one can type$ var=$(( j >= -5 && jsyntax error: 'newline or ;' unexpected
ex2: $ echo \>>
14. Creating archieves14.1. Archiving files : tar command
tar backs up entire directories and files onto a tape device or (more commonly) into a single disk file known as an archive. An archive is a file that contains other files plus information about them, such as their filename, owner, timestamps, and access permissions. tar does not perform any compression by default.
To create a disk file tar archive, use
Syntax: tar -cvf archivename where archivename is the name of the archive and will usually have a .tar extension and files or directories are the files or the directories you want to archive. Here the c option means create, v means verbose (output filenames as they are archived), and f means file.
ex. 1: $ tar cvf arhiva /home/will/work
This command will archive the entire work directory into one file called arhiva located in the current working directory.
To list the contents of a tar archive, use the following syntax :
$ tar -tvf archivename
ex.2: $ tar tvf arhivawill list the content of the archive arhiva (the -t option is the list option and asks the archive to tell you about the contents of the file rather than unpack it ).
To restore files from a tar archive, use the syntax :
$ tar -xvf archivenameex.3: $ tar tvf arhivawill unpack the archive arhiva (the x option is used when extracting your files from the archive).
14.2. Compressing files : compress command
Syntax: compress filename
Files created with the compress command have the file suffix .z .
ex.1: $ compress arhiva
will compress the archive previously created in the previously exemplaes into arhiva.z.
The uncompress command uncompresses the results of a compress command. To use the uncompress command, you issue the command as :
$ uncompress filename.Z14.3. Compressing files : gzip commandSyntax: gzip filenameGzip command does the same thing as compress command. The gzip command (stands for GNU zip) is the original file compression program for GNU/Linux and produce files with a .gz extension.
ex.1: $ gzip arhiva
will compress the file arhiva into file arhiva.gz.To decompress an gzip file, add the d command:
ex. 2: $ gzip d arhiva.gz
UNIX vi editor
1. Introduction to vi
1.1. General considerations
vi (pronounced "vee-eye", short for visual, or perhaps vile) is a display-oriented text editor based on an underlying line editor called ex. Although at the beginning beginners it is found somewhat awkward to use, vi is useful to learn because it is universally available (being supplied with all UNIX systems). It also uses standard alphanumeric keys for commands, so it can be used on almost any terminal or workstation without having to worry about unusual keyboard mappings. System administrators like users to use vi because it uses very few system resources. So the vi editor is by far one of the most used editors in the Unix community today. It has been around for a long time and continues to find new fans at an increasing rate. It's a streamlined, highly functional tool that does not require much memory. 1.2. Getting started
In this document all upper/lower case commands should be carefully noted. Commands in "vi" are case sensitive. represents the entry of a control value. It is executed by holding down the "control key" while pressing the appropriate letter.
To start the editor, from a shell prompt enter
$ vi filename
where filename would be replaced by the name of the file you want to edit.
Example:
$ vi myfile
If the file named already exists, the current contents of the file will be displayed. If the file named doesn't exist, a new file will be created.The main feature that makes vi unique as an editor is its mode-based operation. vi has two modes: command mode and input mode. In command mode, characters you type perform actions (e.g. moving the cursor, cutting or copying text, etc.) In input mode, characters you type are inserted or overwrite existing text.
2. The insert mode
When you begin vi, it is in command mode. To put vi into input mode, press i (insert). You can then type text which is inserted at the current cursor location; you can correct mistakes with the backspace key as you type.Another way of inserting text, especially useful when you are at the end of a line is to press a (append). The first rule to remember is how to exit insert mode. Every time you enter insert mode, you have to remember to press ESC before executing other commands!Here is a table with the most important commands related to the insert mode:
ESC key Exit insert mode
iInsert characters BEFORE cursor position
IInsert characters at BEGINNING of current line (Capital i)
aAppend characters AFTER cursor position
AAppend characters at END of current line
oOpen a new line BELOW current line
OOpen a new line ABOVE current line
3. The command mode
The complexity of vi editor is in the instructions referring the command mode. Due to the amount of commans that can be operated over the vi editor, we prefer to split them in sub-modes regarding their aim. So, we have movement, changing, global editing, searching or special commands.
3.1. Movement sub-mode
The simplest method to move the cursor is to use the arrow keys, up, down, left or right. Other handy movement commands are...fGoes forward a screen at a time
bGoes backwards a screen at a time
GJumps to the end of the file
#GJumps to a specific line number. Example: 3G jumps to line 3
#jJumps downwards a specific line number
#kJumps upwards a specific line number
space bar Moves forward a character at a time
backspace key Moves backwards a character at a time
enter key Drops down a line at a time
$Jumps to end of current line
^Jumps to beginning of current line
wMoves forward one word at a time
bMoves backwards one word at a time
`aJumps1 to marker a
)Jumps2 to the end of the sentence
(Jumps to the beginning of the sentence
} Jumps to the end of the paragraph
{Jumps to the beginning of the paragraph
Comments:
1. The marker notion is defined in section 3.5
2. The sentences is delimited by . ! ?. They have to be separated by at least TWO spaces or have to be on separate rows. 3.2. Changing sub-mode
These are the main commands used for changing the content of the existing text. They are mainly related to replacing and deleting characters and lines.RReplace characters starting at cursor position until ESC
SReplace current line
rxReplace current character with the letter "x"
cwChange the word at the current position up to the first space. Press ESC after new entry
xDelete character at current position
#xDelete several characters starting at current position. Example: 3x deletes 3 characters
dwDelete from character to the end of the current word
ddDelete the current line
#ddDelete a number of lines, starting with current line. Example: 5dd will delete 5 lines
DDelete from cursor to end of the line
d^Delete from cursor to the beginning of the line
d)Delete from cursor to the end of the sentence
d}Delete from cursor to the end of the paragraph
uUndo last command
UUndo all changes to the current line
All the deleted items are temporarily stored to the general buffer, from where they can be inserted back (usually to another location in the text). The buffer is overwritten every delete command. For saving more distinct items, you could send them to other buffers. To give an example, lets say you need to move line 4 and 5 to, positions corresponding to line 23 and respectively 190. For saving time, you should do the following:
At first, you line 4 and put it to buffer a:
add
Next you delete the fifth row, putting it into a different buffer b:
bddNow you may navigate to the position corresponding to line 23, where you insert the content of buffer a:
apAfter that, move to position 190, and type the dual command of above:
bp
This way, you may move the nearby located lines 4 and 5, without navigating to line 23 to place line 4 and, after that, back to line 5 to move this second line.
addDelete current line to buffer a
AddDelete current line; append to buffer a
d`bDelete from current position to marker b (send to general buffer)
pInsert the content of general buffer after the cursor
PInsert the content of general buffer before the cursor
apInsert the content of buffer a after the cursor
You may also save (yank) lines or strings of characters to general or different buffers.yy or YYank line to general buffer
3yyYank the following 3 lines to general buffer
a2yyYank the following 2 lines to buffer a
by`cYank to buffer b from current position to marker c
JJoin the line below to the end of the current line
3.3. Global editing sub-mode (colon mode)
These are the commands that allows you to execute global edit commands, read/write to a file, exit vi and many more options. The global-editing sub-mode is entered by typing the : command.
Note - every command in colon mode follows the start colon symbol :
Global editing or colon sub-mode may be used for many purposes. The most important of these are mentioned below.
One of the most important use for colon sub-mode commands are for saving, writing or exiting a file:
:Start colon sub-mode. You will jump to the last line on the screen where a colon will display and await your next command
wWrite the file saving current changes, but does not exit vi
w filenameWrite the current file to another file name
q!Abort all changes and exit
wqWrite the file and exit
xWrite the file and exit
#,#w filenameWrite a range of lines of from current file to another file. Example: 5,10w file1 will write lines 5 to 10 to a file called file1
#,#w >> filenameAppend a range of lines of from current file to another file
r filenameReads a file and inserts it the line below current position
4r filenameReads a file and inserts it the line below line 4
r filenameReads a file and inserts it the line below current position
One of the main uses of vi is for global replacements purposes:1,$s/thisvalue/withthis/Performs global substitution starting at line 1 to end of file.
1,$s/thisvalue/withthis/gSame as above, except this will perform the substitution as many times as required per line. Without the letter "g" at the end, the command will only perform the substitution once per line. Example: 5,10s/Dan /Daniel /g will change all occurrences of "Dan " to "Daniel " from line 5 through line 10. Note the inclusion of the space character after Dan and Daniel. Without this it would have changed "Dana" to "Daniela"
10,20s/^Dan /George /Changes the occurrence of "Dan " to "George" only if the line STARTS with "Dan "
10,20s/01$/99/Changes the occurrence of "01" to "99" only if the line ENDS with "01"
What if you want to change a date 01/31/94 to /02/28/94 on the current line?
.s/01\/03\/94/02\/28\/94/ The dot at the beginning represents the current line only.
Proceed special characters, i.e. the "/", with a reverse slash "\".
The "\" tells the command to use the NEXT character as a parameter and NOT the command separator.
So if you want to change a "$" in your command you would also proceed it by a "\".
You could also print, delete, copy and paste lines :
x,y pprints line x through line y
.,+x pprints x+1 lines from current line
g/pattern/pprints all lines containing pattern
x,y ddelete from line x to line y
/pattern/ddeletes the next line containing the pattern
g/pattern/ddeletes all the lines containing pattern
x,y m zmoves lines x to y at z position
x,y co zcopies lines x to y at z position
x,z ya byanks rows x to z to buffer b
pu bputs on current cursor position buffer b
Generally, you may execute any command in the colon mode by simply entering: ! commandExecutes a shell command. Example: !pwd will print the current directory.
3.4. Searching sub-mode
You can search a string by entering the search sub-mode. /instance Jumps from the current cursor position to the first instance of
word instance (searches forward)
?instance Jumps from the current cursor position to the last instance of
word instance (searches backwards)
nJumps to the next occurrence of the last find command
NJumps back to the occurrence of the last find command
.Repeats the last change/edit command
If you want, for instance to find the first occurrence of word example, you type /example. The cursor will go then over the first instance of this word, if it exists. Then you may change the word with a new wanted one (lets say name), by typing cwname. After pressing the ESC key, you may navigate to the next instance of word example by typing n. Then, by typing the dot ., the last change is repeated, this occurrence of the word example being replaced by the word name.3.5. Other commands
There a few useful vi commands that are stated in the table below. They couldnt be placed into one of the above groups. mamarks the current position as marker a
gDisplay the current file info, current line number, number of lines in the file and location percentage
...