Linux file command proficiency Guide

Source: Internet
Author: User
Tags egrep
Author: Sheryl calish

Quick tutorial for beginners who are new to Linux file commands

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 articleArticleIt is a "quick tutorial" on Linux file commands, which is provided for users who are new to the operating system or just need to supplement 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 consideredCompositionHardware devices (including keyboards and terminals), directories, commands, and 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, orManPage andWhatisTool. You can useWhatisCommand to access an unfamiliar commandManPage.

 
$ 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 useMan-K(Also knownApropos) And a topic to generate possible commands. For example:

 
$ Man-K files

A useful but often overlooked command can provideManInformation:

 
$ Man

You can use spacebar to browse anyManPage; up arrow will roll up the file .. To exit, enter Q ,!, Or Ctrl-Z.

User Type

Remember that sentenceFamous saying"Are all animals 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 use another user nameSu(From "superuser") log on. To perform tasks such as adding a new user, printer, or file system, you must log on as the root user or useSuCommand and Root User Password switch to 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.

Bash built-in commandsHistoryThe last 500 commands entered are recorded by default. You can enterHistoryTo 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 run this command by running a command from the project at the top of the History List:If there are 53 events in the History list,$! -3Run event No. 51.

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 useEchoCommand, and use a $ symbol to access the value of an environment variable, and then view the value.

 
$ Echo $ home/bluher

AvailableEnvCommand 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 (suchEgrepAndAwk) Uses a wider set of special characters for pattern matching.

File Processing Command

Profiling a file list

LsCommand 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. profile19942-RW-r -- 1 Scalish users 30 Jan 3 test2.out925-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-I. The remaining columns pass through-LTo display normally.
    • 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 we use-H.
    • 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-The list contains a list of hidden files (such as. Profile.

Process files

Movable (MV), Copy (CP) Or delete (RmFiles and directories. Use it wisely-IOption to get confirmation is usually a good idea.

 
$ CP-I LS. Out ls2.outcp: overwrite 'ls2. out '?

MV command is allowed-BOption, which will make a backup copy before moving the file.RmAndCPAccept powerful but dangerous features-RIt will be recursively executed in a directory and its files.

 
$ Rm-IR testrm: descend into Directory 'test '? Y

AvailableMkdirTo create a directory.RmdirTo delete the directory. However, it cannot be used.RmdirTo delete the directory containing files, so useRmAdd-RThe options are usually more convenient.

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,DRepresents the directory, andLLink.
    • The next nine characters are access permissions for three user categories: file owner (2-4), user group (5-7), and others (8-10 ).RIndicates read permission,WIndicates write permission,XIndicates the execution permission on a file. Break number-If any of the nine locations appears, it indicates that this operation is forbidden for users of this category.

AvailableChmodThe command sets 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: Owner User Group Others
Character representation: Rwx R-x R --
Binary representation: 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

UseUmaskCommand to set local file permissions in the/etc/init. Dev file or in the. profile file. 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.

AvailableChownTo modify the File Ownership:

 
$ Chown bluher ls. Out

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

 
$ Chgrp devgrp ls. Out

Here, devgrp is a new user group.

LsIt does not provide text files and binary files. You can useFile *Command.

Rename a file

Two popular methods to assign multiple names to a file are using links andAliasCommand.AliasIt 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

About alias and Its Anti-CommandsUnaliasFor more information, see Bash'sManThe "shell builtin commands" sub-part of the 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

SeparateLnCommand to create a hard link to the file, and use-STo 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,LIndicates 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¹ Ý Filter.SedAndAwkThe command is an example of two filters, because they are discussed in detail in the previous OTN article and will be skipped here.

SuchCat, moreAndLessSuch commands allow you to view the content of a text file from the command line without calling the editor.CatIs the abbreviation of "concatenate", which displays the file content on the standard output (Display) by default. AndCatOne of the most interesting options provided together is-NIt displays the file content with the output row of the serial number.

 
$ Cat-n test. out1 this is a test.

BecauseCatOutput all rows in the file at a time, so you may prefer to useMoreAndLessBecause they all output the content of a screen at a time.LessYesMoreIs an enhanced version, which allows you to use key commands from the VI text editor to enhance File Viewing. For example,DRoll forward,BRoll backwardNLine (ifNYesDOrBPreviously specified ). IsNThe input value is the default value of the subsequent D command.ManThe 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.outanother test. $ CAT test. Out> test2.out $ cat test2.outanother test. This is a test.

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

 
$ Cat <test2.out

Error Message2>And2>To redirect and add, 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

You can use>!Symbol to overload this feature. To disable this feature, use+ OReplace-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.

MPs queue usage|And works 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, fgrepAndEgrepAll rows matching one mode are displayed. 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.

GrepWhich of the following is the most useful option?-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(AlsoGrep-F call) Only search for fixed strings, rather than the regular expression received by grep. WhileEgrepReceives a pattern that contains a larger range of special characters (such as "|", which indicates the condition or operator.

 
$ Egrep 'subject | mailto '*

Search for files

FindThe GNU version of the 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.FindThe basic command format is:

 
$ FindStartdirectory 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-PrintOperation, because if no other operation options are specified, this operation is assumed to be executed. A vertex at the beginning of the directory (.) Will makeFindSearch in your working directory. Two points,..To 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 isGrepUsed Together-ExecOperation:

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

Here, let's run the find command in the current directory,., Find an HTML file,*. HtmlAnd run the following command on the current file (-Exec) Grep command,{}. When using-ExecA semicolon is required for the operation.;This is used to execute other operations when using the find command. Backlash required\And quotation marks to ensure that these items are interpreted by bash so that they are interpreted by commands rather than shell.

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.