Linux file command proficiency Guide (I)

Source: Internet
Author: User
Tags echo command egrep

Although GUI desktops (such as KDE and GNOME) can help users utilize Linux features without having to know about the functions of command line interfaces, more functions and flexibility are often required. Also, basic familiarity with these commands is still necessary to automate certain functions correctly in shell scripts.

This article is a "quick tutorial" on Linux file commands. It is provided for users who are new to the operating system or who only need to add this knowledge. It provides a concise overview of some more useful commands and guidance on their most powerful applications. The following information-combined with some experiments-will allow you to easily master these basic commands. (Note: When a kernel is involved in combination with an Oracle Cluster File System (OCFS), some commands in these commands may behave slightly differently. In this case, Oracle provides an OCFS tool set that provides a better choice for file command applications .)

Note that all examples included here are tested on SUSE Linux 8.0 Professional. Although there is no reason to believe that they will not work on other systems, if there is a problem, you should check your documents to understand possible changes.

Background

Let's review some basic knowledge before going into the specifications.

Files and commands

In Linux/UNIX operating systems, everything is processed as a file: hardware devices (including keyboards and terminals), directories, commands themselves, and of course files. This strange practice is actually the foundation of Linux/UNIX capabilities and flexibility.

Most (almost all) commands are as follows:

Command [option] [source file (s)] [target file]

Get help

One of the most useful commands is those that provide help (especially for those who learn Linux ). Two important sources of information in Linux are the online reference manual, man page, And whatis tool. You can use the whatis command to access the man page of an unfamiliar command.

$ Whatis echo

To learn more about this command, you can use:

$ Man echo

If you do not know the commands required for a special task, you can use man-k (also called apropos) and a topic to generate possible commands. For example:

$ Man-k files

A useful but often overlooked command can provide information about the use of man itself:

$ Man

You can use SPACEBAR to browse any man page. up arrow will roll UP the file .. To exit, enter q ,!, Or CTRL-Z.

User Type

Do you remember the famous saying "All animals are equal, but some animals are more equal than other animals? In the Linux World, root users are in charge of everything.

The root user can log on with another user name su (derived from "superuser. To execute tasks such as adding a new user, printer, or file system, you must log on as the root user or use the su command and root user password to switch to the Super User. System files (including system files that control the initialization process) are ultimately owned by users. Although normal users may be allowed to read them, the right to edit will be left to the root user for system security reasons.

BASH shell

Although other shells are provided, BASH (Bourne Again shell) is the default Shell of Linux. It combines the features of the Bourne shell with the same name as it and the features of the Korn, C, and TCSH shell.

The built-in BASH command history records the last 500 commands entered by default. You can enter history at the command prompt to view them. To retrieve a specific command, you can press up arrow or down arrow at the command prompt, enter its number in the History list, and add "! ", For example:

$! 49

You can also execute this command by running a command from the top project in the History List: if there are 53 events in the History List, $! -3 event number 51 will be executed.

Like other shells in the UNIX/Linux World, BASH uses special environment variables to facilitate system management. For example:

HOME, HOME directory

PATH, which is used by Linux to search for the executable image of the command you entered

HISTSIZE, number of historical events saved by the System

In addition to these reserved keywords, you can also define your own environment variables. For example, if Oracle uses ORACLE_HOME (there are other variables), you must set these variables in your environment for successful Oracle installation.

You can set the variables temporarily at the prompt:

$ HISTSIZE = 100

Alternatively, set the system scope permanently in/etc/profile (root user permission required) or in. profile.

You can use the echo command and a $ symbol to access the value of an environment variable and view the value.

$ Echo $ HOME
/Home/bluher

You can use the env command to view all the current environment variables.

Regular Expressions and wildcards

Many Linux commands use wildcards * and? To match any number of characters or match any single character respectively. The regular expression uses a period (.) to match any single character except the line break. In both cases, square brackets ([]) are used to match character groups. However, the * sign has a similar but different meaning in various situations: although it matches one or more characters in shell, in the regular expression, it matches zero or more instances of the preceding characters. Some commands (such as egrep and awk) Use a wider set of special characters for pattern matching.

File Processing Command

Profiling a file list

The ls command is used to view the list of files in any directory where the user has the execution permission. This command has many interesting options. For example:

$ Ls-liah *
22684-rw-r -- 1 bluher users 952 Dec 28. profile
19942-rw-r -- 1 scalish users 30 Jan 3 20:00 test2.out
925-rwxr-xr-x 1 scalish users 378 Sep 2 2002 test. sh

The above list shows eight columns:

Column 1st indicates the inode of the file, because we use the-I option. The remaining columns are displayed normally using the-l option.

The 2nd column displays the file type and file access permissions.

The number of links displayed in the 3rd column, including directories.

Columns 4th and 5th show the file owner and group owner. Here, the owner "bluher" belongs to the group "users ".

The file size is displayed in the 6th column (unit: the displayed unit, rather than the default number of bytes, because the-h option is used.

The 7th column shows the date (it looks like three columns), including month, day, and year, and the time of the day.

The file name is displayed in the 8th column. Use-a in the option list to include a list of hidden files (such as. profile) in the list.

Process files

You can move (mv), copy (cp), or delete (rm) files and directories. It is usually a good idea to use the-I option wisely for confirmation.

$ Cp-I ls. out ls2.out
Cp: overwrite 'ls2. out '?

The mv command allows you to use the-B option, which will make a backup copy before moving the file. Rm and cp accept powerful but dangerous-r options that will be recursively executed in a directory and its files.

$ Rm-ir Test
Rm: descend into directory 'test '? Y

You can use mkdir to create a directory and rmdir to delete the directory. However, because rmdir cannot be used to delete directories containing files, it is usually easier to use the rm plus-r option.

For security reasons, all files are owned and protected. The file access permission (or file mode) contains the same 10 characters as mentioned earlier:

The first character indicates the file type. The most common is-represents a file, d represents a directory, and l represents a link.

The next nine characters are access permissions for three user categories: file owner (2-4), user group (5-7), and others (8-10 ), r indicates the read permission, w indicates the write permission, and x indicates the execution permission on a file. Break number-if any of the nine locations appears, this operation is prohibited for users of this category.

You can use the chmod command to set the access permission through the character symbol or binary mask. To use the binary mask, you must convert the character representation of the three permission groups to the binary format and convert it to the octal format:

User Type: other user groups of the owner
Character representation: rwx r-x r --
Binary: 111 101 100
Octal representation: 7 5 4

Grant the write permission to the user group. You can use:

Chmod g + w test. sh or chmod 774 test. sh

Use the umask command to set local file permissions in the/etc/init. dev file within the system or in the. profile file by default. This command indicates that the default permission is obtained by subtracting 777 from the number:

$ Umask 022

This will generate a default 755 File Permission for all new files created by the user.

You can use chown to modify the File Ownership:

$ Chown bluher ls. out

Here, bluher is the new file owner. Similarly, the Group membership will be modified as follows:

$ Chgrp devgrp ls. out

Here, devgrp is a new user group.

Ls does not provide text and binary information. To learn this information, you can use the file * command.

Rename a file

Two popular methods to assign multiple names to a file are using links and alias commands. Alias can be used to create a more convenient name for a longer command:

$ Alias ll = 'LS-l'
$ Ll

Note the use of single quotes, which enables BASH to pass the project to the alias, rather than estimate it by itself. Aliases can also be abbreviated as long path names:

$ Alias jdev9i =/jdev9i/jdev/bin/jdev

For more information about alias and Its Anti-command unalias, see the "shell builtin commands" sub-part on the BASH man page. In the last example, an environment variable is defined to achieve the same result.

$ Export JDEV_HOME =/jdev9i/jdev/bin/jdev
$ Echo $ JDEV_HOME
/Jdev9i/jdev/bin/jdev
$ JDEV_HOME

The link allows several file names to reference a single source file in the following format:

Ln [-s] fileyouwanttolinkto newname

Separate ln command to create a hard link to the file, and use the-s option to create a symbolic link. In short, a hard link can hardly be separated from the original file (except the inode of the two files will be the same ). Symbolic Links are easy to differentiate because they appear in a long file list and use-> to indicate the source file. l indicates the file type.

View and find files

File Filter

Commands used to read the file content and perform operations on the file content are sometimes called 1y filters. The sed and awk commands are examples of two filters, because they are discussed in detail in the previous OTN article, which will be skipped here.

Commands such as cat, more, and less allow you to view the content of a text file from the command line without calling the editor. Cat is short for "concatenate", which displays the file content on the standard output (Display) by default. One of the most interesting options provided with cat is the-n option, which uses the output row of the number to display the file content.

$ Cat-n test. out
1 This is a test.

Because cat outputs all rows in a file at a time, you may prefer more and less, because they all output the content of a screen at a time. Less is an enhanced version of more. It allows you to use key commands from the vi text editor to enhance File Viewing. For example, d rolls forward, B rolls N rows backward (if N is specified before d or B ). The value entered for N is the default value of the subsequent d command. The man page utility uses less to display instructions.

Redirection and MPs queue

Redirection allows you to redirect command output to a file, rather than standard output. Similarly, you can also redirect the input. Standard redirection symbol> Create a new file.> Symbol to add the output to an existing file:

$ More test2.out
Another test.
$ Cat test. out> test2.out
$ Cat test2.out
Another test.
This is a test.

You can use the <symbol to redirect the standard input to the file:

$ Cat <test2.out

Use 2> and 2> to redirect and add error messages. The format is as follows:

$ Command 2> name_of_error_file

To avoid overwriting an existing file unintentionally, use the BASH built-in command set:

$ Set-o noclobber

Can be used between commands and output files>! Symbol to overload this feature. To disable this feature, replace-o with + o.

Redirection works between a command and a file, or between a file and a file. One of the Redirect statements must be a file.

Pipeline use | symbol and work between commands. For example, you can use the following method to directly send the output of a command to a printer:

$ Ls-l * | lpr

You can use the following method to quickly find a command in the History List:

$ History | grep cat

More Filters

Grep, fgrep, and egrep both show rows that match a pattern. All three commands search for the specified mode in the file. This is useful if you cannot remember the name of the required file. The basic format is:

Grep [options] PATTERN [FILE...]
$ Grep-r 'subobject' nsmail
The CTRL-Z terminates the above or any other command.

The most useful option of grep may be-s. If you search for system files by any identity except the root user, an error message is generated for each file that you do not have access. This command disables those messages.

Fgrep (also called with grep-F) Only searches for fixed strings, rather than the regular expression received by grep. While egrep receives a pattern that contains a larger range of special characters (such as "|", which indicates the condition OR operator.

$ Egrep 'subject | mailto '*

Search for files

The GNU version of the find command is very powerful, flexible, and more inclusive than the classic version on UNIX systems. It is very useful for tasks involving directory structures, including searching and executing commands on files. The basic format of the find command is:

$ Find startdirectory options matchcriteria [actionoptions]

If you know the file name, or even part of the name, but do not know its directory, you can do this:

$ Find.-name 'test *'
./Test
./Jdevhome/mywork/EmpWS/EmpBC4J/test

Unlike the classic UNIX system, you do not need to add the-print operation at the end of Linux, because if no other operation options are specified, this operation is assumed to be executed. A dot (.) at the beginning of the directory will make find start searching in your working directory. Start searching in the parent directory. You can start searching in any directory.

Note that you can use wildcards as part of the search criteria (you only need to enclose the entire project in single quotes ).

$ Find.-name 'test * '-print
./Test. out
./Test2.out

Displays a series of files with the. out extension:

$ Find/home-name '*. out'

Remember, unless you run this command as a Super User, you may get many "Permission denied" error messages.

One of the most powerful search tools is the-exec operation used with grep:

$ Find.-name '*. html'-exec grep 'mailto: foo@yahoo.com '{}\;

Here, let's run the find command in the current directory to find an html file, *. html, and execute the (-exec) grep command on the current file ,{}. When you use the-exec operation, a semicolon is required. This is used to execute other operations when you use the find command. Backlash \ and quotation marks are required to ensure that these items are interpreted by BASH so that they are interpreted by commands rather than shell.

Get started with Linux file commands

Many useful commands and powerful methods are provided in Linux, which cannot be described here. In addition, there are usually multiple methods to complete many tasks.

We have seen some of the most common and enlightening Linux file commands. Understanding these basics but key tools will bring your Linux learning to the fast track. With the man page on your hand and the enthusiasm of the experiment, you now have enough information to start exploring the power of Linux File Operations.

In my next article, I will provide a similar description of Linux system commands.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.