operate files and directories

 

At this point,we are ready for some real work!This chapter will introduce the following commands:

cp:Copy files and directories

mv:move/rename files and directories

mkdir:create directories

rm:remove files and directories

ln:create hard and symbolic links

These five commands are among the most frequently used Linux commands.They are used fo manipulating both files and directories.

Now,to be frank(坦白地),some of the tasks performed by these commands are more easily done with a graphical file manager.With a file manager,we can drag and drop a file from one directory to another,cut and paste files,delete files,etc.So why use these old command line programs?

The answer is power and flexibility.While it is easy to perform simple file manipulations with a graphical file manager,complicated tasks can be easier with the command line programs.For example,how could we copy all the HTML files from one directory to another,but only copy files that do not exist in the destination directory or are newer than the versions in the destination directory?Pretty hard with a file manager.Pretty easy with the command line:

Wildcards(通配符)

Before we begin using our commands,we need to talk about a shell feature that makes these commands so powerful.Since the shell uses filenames so much,it provides special characters to help you rapidly specify groups of filenames.These special characters are called wildcards.Using wildcards (which is also known as globbinh) allow you to select filenames based on patterns of characters.The table below lists the wildcards and what they select:

Table 5-1:Wildcards

Wildcard Meaning
*Matches any characters
?Matches any single character
[characters]Matches any character that is a member of the set characters
[!characters]Matches any character that is not a member of the set characters
[[:class:]]Matches any character that is a memeber of the specified class

Table 5-2 lists the most commonly used character classes:

Table 5-2:Commonly Used Character Classes

Character ClassMeaning
[:alnum:]Matches any alphanumeric(文学数字的) character
[:alpha:]Matches any alphabetic(字母的) character
[:digit:]Matches any numeral
[:lower:]Matches any lowercase(小写字母) letter
[:upper:]Matches any uppercase(大写字母) letter

Using wildcards makes it possible to construct(构成,组成) very sophisticated(精密的,精准的) selection criteria for filename.Here are some examples of patterns and what they match:

Table 5-3:Wildcard Examples:

PatternMatches
*All files
g*All file beginning with "g"
b*.txtAny file beginning with "b" followed by any characters and ending with ".txt"
Data???Any file beginning with Data and followed by exactly three characters
[abc]*Any file beginning with either an "a",a"b",a"c"
BACKUP.[0-9][0-9][0-9]Any flle beginning with "BACKUP." followed by three exactly numerals
[[:upper:]]*Any file beginning with an uppercase letter
[![:digit:]]*Any file not beginning with a numeral
*[[:lower:]123]Any file ending with a lowercase letter or the numerals "1","2",or"3"

Widcards can be used with any command that accepts filenames as arguments,but we'll talk more about that in Chapter 8.

Character Ranges

If you are coming from another Unix-like environment or have been reading some other books on this subject,you may have encountered the [A-Z] or the [a-z] character range notations.These are traditonal Unix notations and worked in older versions of Linux.They can still work,but you have to very careful with them because they will not produce the expected results unless properly configured.From now on ,you should avoid using them and use character classes instead.

Wildcards are especially valuable not only because they are used so frequently on the command line,but are also supported by some graphical file managers.

  • In Nautilus(the file manager for GNOME),you can select files using the Edit/Select Pattern menu item.Just enter a file selection pattern with wildcards and the files in the currently viewed directory will be highlighted for selection.
  • In Dolphin and Konqueror(the file managers for KDE),you can enter wildcards directory on the location bar.For example,if you want to see all the files starting with a lowercase "u" in the /usr/bin directory,type "/usr/bin/u*" into the location bar(地址栏) and it will display the result.

Many ideas originally found in the command line interface make their way into the graphical interface,too.It is one of the many things that make the Linux desktop so powerful.

 

mkdir-create directory

The mkdir command is used to created directories.It works like this:

A note on notation:(注意表示用法:)When three periods follow an argument in the description of a command (as above),it means that the argument can be repeated,thus:

would create a single directory named "dir1",while

would create three directories name "dir1","dir2","dir3".

 

cp-copy files and directories

The cp command copies files or directories.It can be used two different way:

to copy the single file or directory "item1" to file or directory "item2" and:

to copy multiple items(either files or directories) into a directory.

 

Useful options and instances

Here are some of the commonly used options (the short option and equivalent long option) for cp:

Table 5-4:cp Options

OptonMeaning
-a,--archiveCopy the files and directories and all of their attributes,including ownerships and permissions.Normally,copies take on the default attributes of the user performing the copy
-i,--interactiveBefore overwriting an existing file,prompt the user for confirmation.If this option is not specified,cp will silently overwrite files.
-r,-recursiveRecursively copy directories and their contents.This option (or the -a option) is required when copying directories.
-u,--updateWhen copying files from one directory to another,only copy files that either don't exist,or are newer than the existing corresponding files,in the destionation directory
-v,--verboseDisplay information messages as the copy is performed.

Table 5-5:cp Examples

CommandResults
cp file1 file2Copy file1 to file2.If file2 exists,it is overwritten with the contents of file1.If file2 does not exist,it is created.
cp -i file1 file2Same as above,expect that if file2 exists,the user is prompted before it is overwritten
cp file1 file2 dir1Copy file1 and file2 into directory dir1. dir1 must already exist.
cp dir1/* dir2Using a wildcard, all the files in dir1 are copied into dir2. dir2 must already exist.
cp -r dir1 dir2Copy the contents of directory dir1 to directory dir2. If directory dir2 does not exist, it is created and, after the copy, will contain the same contents as directory dir1. If directory dir2 does exist, then directory dir1 (and its contents) will be copied into dir2.

 

mv-move and rename the file

The mv command performs both file moving and file renaming,depending on how it is used.In either case,the original filename no longer exists after the operation.mv is used in much the same way as cp:

to move or rename file or directory “item1” to “item2” or:

to move one or more items from one directory to another.

Useful options and instances

mv shares many of the same options as cp:

Table 5-6:mv options

OptionMeaning
-i --interactiveBefore overwriting an existing file, prompt the user for confirmation. If this option is not specified, mv command will silently overwrite files
-u --updateWhen moving files from one directory to another, only move files that either don't exist, or are newer than the existing corresponding files in the destination directory.
-v --verboseDisplay informative messages as the move is performed.

Table 5-7:mv Examples

mv file1 file2Move file1 to file2. If file2 exists, it is overwritten with the contents of files. If file2 does not exist, it is created. In either case, file1 ceases to exist.
mv -i file1 file2Same as above, except that if file2 exists, the user is prompted before it is overwritten.
mv file1 file2 dir1Move file1 and file2 into dirctory dir1. dir1 must already exist.
mv dir1 dir2if directory dir2 does not exist, create directory dir2 and move the contents of directory dir1 into dir2 and delete directory dir1. if directory dir2 does exist, move directory dir1 (and its contents) into directory dir2.

 

rm - delete file and directory

The rm command is used to remove(delete)files and directories:

where "item" is one or more files or directories.

Useful options and instances

Here are some of the common options for rm:

Table 5-8:rm Options

OptionMeaning
-i, --interactiveBefore deleting an existing file, prompt the user for confirmation. If this option is not specified, rm will silently delete files.
-r, --recursiveRecursively delete directories. This means that if a directory being deleted has subdirectories, delete them too. To delete a directory, this option must be specified.
-f, --forceIgnore nonexistent files and do not prompt. This overrides the --interactive option.
-v, --verboseDisplay informative messages as the deletion is performed.

Table 5-9:rm Examples

CommandResults
rm file1Delete file1 silently
rm -i file1Same as above, except that the user is prompted for confirmation before the deletion is performed.
rm -r file1 dir1Delete file1 and dir1 and its contents.
rm -rf file1 dir1Same as above, except that if either file1 or dir1 do not exist, rm will continue silently.

 

Be Careful with rm!

Unix-like operating systems such as Linux do not have an undelete command.Once you delete something with rm,it's gone.Linux assumes you're smart and you know what you're doing.

Be particularly careful with wildcards.Consider this classic example.Let's say you want to delete just the HTML files in a directory.To do this,you type:

rm *.html

which is correct,but if you accidentally place a space between the "*" and the ".html" like so:

rm* .html

the rm command will delete all the files in the directory and then complain that there is no file called ".html".

Here is a useful tip.Whenever you use wildcards with rm(besides carefully checking your typing!),test the wildcard first with ls.This will let you see the files that will be deleted.Then press the up arrow key to recall the command and replace the ls with rm.

 

ln - create link

The ln command is used to create either hard or symbolic links.It is used in one of two ways:

 

to create a hard link,and:

 

to create a symbolic link where “item” is either a file or a directory.

 

Hard links

Hard links are the original Unix way of creating links,compared to symbolic links,which are more modern.By default ,every file has a single hard link that gives the file its name.When we create an additonal directory entry for a file.Hard links have two important limitations:

1.A hard link cannot reference a file outside its own file system.This means a link may not reference a file that is not on the same disk partition as the link itself.

2.A hard link may not reference a directory

A hard link is indistinguishable from the file itself.Unlike a symbolic link,when you list a directory containing containing a hard link you will see no special indication of the link.When a hard link is deleted,the link is removed but the contents of the file itself continue to exist(that is ,its space is not deallocated) until all links to the file are deleted.It is important to be aware of hard links because you might encounter them from time to time,but modern practice prefers symbolic links,which we will cover next.

Symbolic links

Symbolic links were created to overcome the limitations hard links.Symbolic links work by creating a special type of file that contains a text pointer pointer to the referenced file or directory.In this regard,they operate in much the same ways as a Windows shortcut though of course,they predate(提早日期,居先) the Windows feature by many years;

 

A file pointed to by a symbolic link,and the symbolic link itself are largely indistinguishable from one another.For example,if you write some something to the symbolic link,the referenced file is also written to.However when you delete a symbolic link,only the link is deleted,not the file itself.If the file is deleted before the symbolic link,the link will continue to exist,but will point to nothing.In this case,the link is said to be broken.In many implementations,the ls command will display broken links in a distinguishing color,such as red,to reveal(透露) their presence(存在).

The concept of links can seem very confusing,but hang in there.We're going to try all this stuff and it will,hopefully,become clear.

 

Create playground(Combat exercise with live ammunition(实战演习))

Since we are going to do some real file manipulation(操作),let's build a safe place to "play" with our file manipulation commands.First we need a directory to work in.We'll create one in our home directory and call it "playground."

 

Create directory

The mkdir command is used to create a directory.To create our playground directory we will first make sure we are in our home directory and will then create the new directory:

To make our playground a little more interesting.let's create a couple of directories inside it called "dir1" and "dir2".To do this,we will change our current working directory to playground and execute another mkdir:

Notice that the mkdir command will accept multiple arguments allowing us to create both directories with a single command.

### copy files

Next,let's get some data into our playground.We'll do this by copying a file.Using the cp command,we'll copy the passwd file from the /etc directory to the current working the directory:

Notice how we used the shorthand for the current working directory,the single trailing period.So now if we perform an ls,we will see our file:

Now ,just for fun,let's repeat the copy using the "-v" to see what it does:

The cp command performed the copy again,but this time displayed a concise(简明的) message indicating(指示) what operation it was performing.Notice that cp overwrote the first copy without any warning.Again this is a case of cp assuming that you know what you're doing.To get a warning,we'll include the "-i"(interactive) option:

Responding to the prompt by entering a "y" will cause the file to be overwritten,any other character (for example,"n") will cause cp to leave the file alone.

 

Move and rename files

Now,the name "passwd" doesn't seem very playful and this is a playground,so let's change it to something else:

Let's pass the fun around a  little by moving our renamed file to each of the directories and back again:

to move it first to directory dir1,then:

to move it from dir1 to dir2,then:

to finally bringing it back to the current working directory.Next,let's see the effect of mv on directories.First we will move our data file into dir1 again:

then move dir1 into dir2 and confirm it with ls:

 

 Note that since dir2 already existed,mv moved dir1 into dir2.If dir2 had not existed,mv would have renamed dir1 to dir2.Lastly,let's put everything back:

create hard link

Now we'll try some links.First the hard links.We'll create some links to our data file like so:

So now we have four instances of the file "fun".Let's take a look our playground directory:

One thing you notice is that the second fileld in the listing for fun and fun-hard both contain a "4" which is the number of hard links that now exist for the file.You'll remember that a file will always have at least one because the file's name is created by a link.So,how do we know that fun and fun-hard are,in fact,the same file?In this case,ls is not very helpful.While we can see that fun and fun-hard are both the same size(field 5) ,our listing provides no way to be sure.To solve this problem,we're going to have to dig(探究) a little deeper.

 When thinking about hard links,it is helpful to imagine that files are made up of two parts:the data part containing the file's contents and the name part which holds the file's name.When we created hard links,we are actually creating additional name parts that all refer to the same data part.The system assigns a chain of disk blocks to what is called an inode,which is then associated with the name part.Each hard link therefore refers to a specific inode containing the file's contents.

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!表示还是不懂这个硬链接啊

The ls command has a way to reveal this information.It is invoked with the "-i" option:

In this version of the listing,the first field is the inode number and,as we can see,both fun and fun-hard share the same inode number,which confirms they are the same file.

 

Create symbolic links

Symbolic links were created to overcome the two disadvantages of hard links:hard links cannot span(跨越) physical devices and hard links cannot reference directories,only files.Symbolic links are a special type of file that contains a text pointer to the target file or directory.

Creating symbolic links is similar to creating hard links:

The first example is prettty straightforward,we simply add the "-s" option to create a symbolic link rather than a hard link.(所以创建硬链接和软链接的区别就在于-s)But what about the next two?Remember,when we create a symbolic link,we are creating a text description of where the target file is relative to the symbolic link.It's easier to see if we look at the ls output:

The listing for fun-sym in dir1 shows that is it a symbolic link by the leading "l" in the first field and that it points to "../fun",which is correct.Relative to the location of fun-sym,fun is in the directory above it.Notice too,that the length of the symbolic link file is 6,the number of characters in the string "../fun" rather than the length of the file to which it is pointing.

When creating symbolic links ,you can either use absolute pathnames:

 

or relative pathnames,as we did in our earlier example.Using relative pathnames is more desirable because it allows a directory containning symbolic to be renamed and/or moved without breaking the links.

In addition to regular files,symbolic links can also reference directories:

 

Move flles and directories

As  we covered earlier,the rm command is used to delete files and directories.We are going to use it to clean up our playground a little bit.First,let's delete one of our hard links:

That worked as expected.The file fun-hard is gone and the link count shown for fun is reduced from four to three,as indicated in the second field of the directory listing.Next,we'll delete the file fun,and 

Enter "y" at the prompt and file is deleted.But let's look at the output of ls now.Noticed what happened to fun-sym?Since it's a symbolic link pointing to a now-nonexistent file,the link is broken:

Most Linux distributions configure ls to display broken links.On a Fedora box,broken links are displayed in blinking red text! The presence of a broken link is not,in and of itself dangerous but it is rather messy.If we try to use a broken link we will see this:

Let's clean up a little.We'll delete the symbolic links:

One thing to remember about symbolic links is that most file operations are carried out on the link's target,not the link itself.rm is an exception.When you delete a link,it is the link that is deleted,not the target.

Finally,we will remove our playground.To do this,we will return to our home directory and use rm with the recursive option(-r) to delete playground and all of its contents,including its subdirectories:

The file managers in both GNOME and KDE provide an easy and automatic method of creating symbolic links.With GNOME,holding the Ctrl+Shift keys while dragging a file will create a link rather than copying (or moving)the file.In KDE,a small menu appears whenever a ifle is dropped,offering a choice of copying,moving,or linking the file.

 

Sum-up

We've covered a lot of ground here and it will take a while to fully sink in (渗入,完全被理解).Perform the playground exercise over and over until it makes makes sense. It is important to get a good understanding of basic file mainpulation(操作) commands and wildcards.Feel free to expand on the playground exercise by adding more files and directories,using wildcards to specify files for various operations.The concept of links is a little confusing at first,but take the time to learn how they work.They can be a real lifesaver(救星).

 

转载于:https://www.cnblogs.com/itmeatball/p/7512641.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值