Basic Shell File Manipulation


At the heart of using any operating system is the ability to work with filescopying, moving, renaming, creating, and deleting them. Modern graphical operating systems have sophisticated visual metaphors for these tasks, such as dragging file icons in and out of folders. However, on the command line, such file operations require the use of specific commands.

Most of FreeBSD's file-manipulation tools are analogous to similar tools in MS-DOS. If you've worked with MS-DOS before, most of this chapter will come fairly easily to you. If you haven't worked with MS-DOS before, some background information is necessary.

How FreeBSD Stores Files

Like most other modern operating systems, FreeBSD stores files in a hierarchal tree structure. You can think of the FreeBSD filesystem as a filing cabinet in an office, and you can think of each volume on the hard disk as a single drawer in the filing cabinet. FreeBSD's structural hierarchy is organized into multiple top-level directories, or mount points, where disk volumes are attached, and inside each volume are any number of directories (or "folders" as they are often known).

Directories can contain files as well as other directories. These directories and files are analogous to the folders and papers in a drawer. Windows and Macintosh systems both use this same type of filing system. The only real difference is that in Windows and Mac OS X, just as in GNOME or KDE under FreeBSD, you see a graphical representation of folders and files in a graphical file manager. From the FreeBSD command line, you see only a textual representation of these items.

When you log in to FreeBSD at the command line of a shell, you are placed in your home directory, which is located a few levels down from the topmost directory of the system disk. This behavior is the same as in Mac OS X and modern versions of Windows when you summon their respective command-line prompts, as both those systems manage multiple users in the UNIX style by keeping all users' home folders inside a specialized directory on the system disk. You'll learn the details of directory structures in Chapter 12, "The FreeBSD Filesystem." For now, you need only be concerned with your home directory.

Each user on a UNIX system (with certain exceptions) has his own home directory. Your home directory is like your own filing cabinet drawer or your own private "virtual hard disk." Here, you can create and delete files, copy files, move files, and create and remove directories. Your home directory is your personal space on the FreeBSD system, which no other user (except for root) can view, unless you configure parts of it otherwise. Being able to manage the files and directories in your home directory is an important skill. The next few sections take a look at the various commands available to manage your files and directories.

Listing Directory Contents

Use the ls command to list the contents of the directory you are in. Invoked with no options, the ls command produces output similar to the following:

# ls Mail     letter-to-boss     program     proposal-draft fbu      mail               program.c


By itself, this output is not very usefulit tells us nothing about the contents of the files, or even whether they are files or directories. ls supports several options to modify its default behavior. One of the most useful is the -F option, which provides you with more information on the type of each file in the list. Here's an example:

# ls -F Mail/     letter-to-boss    program*     proposal-draft fbu@      mail/             program.c


Now you know a little bit more about the entries in the list. Here is what each symbol following the various files means:

Symbol

Description

/

The item is a subdirectory of the current directory.

*

The item is an executable binary file or script.

@

The item is a link to another location on the hard disk. This is analogous to shortcuts in Windows or to aliases in Mac OS X.


Notice the executable file program. Unlike Windows, FreeBSD does not require a file to have a .com, .exe, or .bat extension to denote it as being executable. Whether a file is executable is a "permissions" bit that is stored along with the file as an attribute. You will almost never see an executable FreeBSD file with an .exe or .com extensionit's not necessary.

This list does not include all the symbols that ls -F can reveal. Type man ls and look at the -F option for a complete list.

Modern versions of the ls command also support the -G option, which tells ls to use different colors to denote different types of files. Not all terminals can display colors, though, and as a general rule, an xterm terminal window cannot display colors unless it is configured as a color xterm. (Do this by setting the TERM variable to xterm-color; see Chapter 9 for details on setting variables.) However, the console terminal can display colors by default.

By default, ls does not display hidden files, which are hidden by virtue of their names beginning with a period (they're also known as dotfiles). To display hidden files, use ls with the -a option:

# ls -a .             .forward     .mailrc         ..profile       Mail ..            .hushlogin   .mysql_history  .project        fbu .addressbook  .login       .rhosts         .login.conf     mail .muttrc       .sh-history  .cshrc          .mail_aliases


Most of these hidden files are configuration files that store various types of information, such as profile information on how you want your shell set up, your address book for the mail program, and a list of the commands you have typed for the history functions of the shell. There are two main benefits to having these files hidden:

  • They don't clutter up the directory during normal operation.

  • It's more difficult to accidentally delete important configuration files because dotfiles are not matched by shell wildcard operators when used by themselves.

If you want more detail about the files and directories in the list, use the -l option, as shown in Listing 8.3.

Listing 8.3. Sample Output of ls -l

# ls -l total 3 drwx------ 2 btman btman   512 Feb 15 16:04 Mail lrwxr-xr-x 1 btman btman    15 Mar 20 06:55 fbu -> /home/btman/documents/books/fbsd -rw-r--r-- 1 btman btman   782 Mar 15 09:21 letter-to-boss drwx------ 2 btman btman   512 Mar 24 15:12 mail -rwx------ 1 btman btman 15221 Feb 21 18:11 program -rw-r--r-- 1 btman btman  1571 Feb 21 17:51 program.c -rw-r--r-- 1 btman btman  2521 Feb 25 18:51 proposal-draft

Each entry has six different fields of information. From left to right, they are as follows:

  • Permissions and other file attributes The first field in the ls -l listing tells you the permissions and attributes of the file. This field is covered in detail in the section titled "File Ownership" in Chapter 13. For now, simply be aware that the information in this field tells you whether the file can be read, modified, or executed as a command.

  • Number of links This field contains the number of links that exist to the file. Every regular file contains at least one link, which is to itself, and every directory contains at least two linksone to itself and one to its parent.

  • Username of the file's owner and Name of the file's owner group These two fields are covered in detail in Chapter 13. For now, be aware that these fields tell you who the owner of the file is and what group the file belongs to.

  • Size of the file This is the size of the file in bytes.

  • Last modification time This is the date and time the file was last modified.

  • Name of the file This is the name of the file. Files that look like the following are links:

    fbu -> /home/btman/documents/books/fbu

    In this case, the entry fbu is actually a link to /home/btman/documents/books/fbu. I can use this link any time I want to reference the directory rather than having to type the entire pathname of the directory.

The ls command can take numerous different options at once. For example, combine l (long listing), -t (sort by last-modified time), and r (sort in reverse order) to get a listing of the files in the directory sorted so that you can easily tell which files have been modified most recently:

# ls -lrt /var/spool/mqueue/ total 180 -rw-------  1 root  daemon  131913 Apr 19  2005 dfg3J6hRq61454 -rw-------  1 root  daemon    4436 Sep 25 18:16 dfg8Q1GmF96201 -rw-------  1 root  daemon    2922 Sep 27 08:05 dfg8RF56F87464 -rw-------  1 root  daemon     283 Sep 27 20:54 dfg8S3s6p77032 -rw-------  1 root  daemon     336 Sep 28 07:09 dfg8SE98Z23923 -rw-------  1 root  daemon     320 Sep 28 11:59 dfg8SIxUv57877 -rw-------  1 root  daemon     344 Sep 29 07:37 dfg8TEbE365707 -rw-------  1 root  daemon     360 Sep 29 10:22 dfg8THMim85609 -rw-------  1 root  daemon     306 Sep 29 11:00 dfg8TI07g90919 -rw-------  1 root  daemon     246 Sep 29 13:34 dfg8TKYvp14024


Moving Around the Filesystem

The cd command is used to "change directory" from one location to another in the filesystem. You can give it destination directory names in several forms, as shown in Table 8.2.

Table 8.2. Usage of the cd Command

Command

Result

cd

Instantly takes you to home directory.

cd /

Directories that begin with / are known as absolute paths. They always start at the root directory of the system (which is the very top directory). A / by itself takes you to the root directory.

cd /usr/local/bin

Takes you to the directory bin, located under the directory local, which is located under the directory usr, which is located under the root (top) directory.

cd bin or cd ./bin

Takes you to the bin directory (if there is one) located directly under whatever directory you currently happen to be in. If there is no such directory, cd returns an error. Directories or filenames that do not begin with / are relative to the current directory you are in. The ./ is not required, but can be a good habit to get into.

cd .. or cd../

The special .. notation means the parent directory of the directory you are currently in. This takes you to the directory one level above where you are right now. The trailing slash is not required.

cd ../bin

Takes you to the directory bin, if one is located in the parent directory of the directory you are currently in.

cd ../../bin

Takes you to the directory bin, located two levels above the directory you are currently in.


Tip

Sometimes, it's easy to forget where you are in the filesystem hierarchy. The pwd ("present working directory") command prints the current directory on your screen. Use it whenever you need to refresh your memory about where you are. (Yes, you can set your shell prompt to show you where you are. You'll learn how in Chapter 9.)


Copying Files and Directories

Use the cp command to copy files from one place to another. It takes as its arguments a list of files to copy, followed by where to copy the files. If you specify more than one file to copy or use a wildcard, the destination must be a directory. A few examples are shown in Table 8.3.

Table 8.3. Usage of the cp Command

Command

Result

cp file1 file2

Copies an existing file called file1 to a new file called file2.

cp file1 /archive/

Copies file1 into the directory archive, which is a subdirectory of the root directory. (The trailing slash is not required, but it's good rigorous practiceif the directory archive doesn't exist, you'll get an error message rather than the file being copied to a new file called archive.)

cp file1 mystuff/newfile

Copies file1 to the directory mystuff in the current directory. If newfile is the name of an existing subdirectory of mystuff, file1 will be copied into the subdirectory newfile. If newfile is not a subdirectory, file1 will be copied to the subdirectory mystuff and given the name newfile.

cp file1 file 2 /archive/

Copies file1 and file2 to the directory archive, located under the root directory.


Caution

By default, the cp command simply overwrites the contents of an existing file if you accidentally copy a file to a filename that already exists. For example, cp file1 file2 overwrites file2 with the contents of file1 if file2 already exists. You can use the -i (interactive) option with cp to cause it to ask you before overwriting any existing files.


If you want to recursively copy a directory and everything under it, including subdirectories, to another location, use the -R option to cp. Here's an example:

# cp -R dir1 dir2


This copies everything under dir1 to a new directory called dir2. If dir2 already exists, a new directory is created under dir2 called dir1, and the contents are placed there. If dir1 already exists in dir2, the contents of dir1 in the current directory are added to the dir1 directory under the dir2 directory. Any files in the directory that have the same name are overwritten by the copies, so be careful when using the -R option (or combine it with the -i option so that you are warned before overwriting anything). Also note that the newly copied files will have the same permissions as the originals, as long as you own them. The cp R command ignores your umask, or the default permissions that are used to create new files. Use the -p option (cp -Rp) to ensure that all permissions are preserved.

Caution

Be careful that you do not accidentally insert special characters (such as space, *, ; etc) when using shell commands. For example:

# cp -R /* /old


This command recursively copies everything in the root directory to a subdirectory called old, which is also in the root directory. Of course, this also means that the contents of old are copied into a subdirectory in old called "old." The result is a loop that copies the contents of old indefinitely. On a fast hard disk, this can quickly fill up the entire disk.


Moving and Renaming Files and Directories

Moving and renaming items is the same operation in UNIX; the mv ("move") command is what you use for either purpose. Some examples are shown in Table 8.4.

Table 8.4. Usage of the mv Command

Command

Result

mv file1 file2

Renames file1 to file2.

mv /dir1 /dir2

Renames dir1 to dir2. Generates an error message if dir2 already exists and is not empty.

mv file1 /dir2/

Moves file1 into the dir2 directory, which is located under the root directory.

mv file1 /dir2/file2

file1 is moved into the /dir2 directory and renamed file2.


Deleting Files and Directories

To delete files, use the rm ("remove") command. With no options, rm deletes the list of files it is given on its command line. It does not delete directories. If you want to delete a directory and everything under that directory, use the -R option with rm. Table 8.5 shows some examples of using the rm command.

Table 8.5. Usage of the rm Command

Command

Result

rm file1

Deletes file1.

rm file1 file2

Deletes file1 and file2.

rm -R dir1

Deletes the directory dir1 and everything under it.


Table 8.6 shows a list of some (but not all) of the other options supported by the rm command.

Table 8.6. Options for Use with the rm Command

Option

Result

-f

Causes rm to force the deletion without asking questions, even if the file is marked read-only. Use this option with care.

-i

Prompts before deleting each file. Useful when using rm with wildcards (more on that later) or with the -R option.

-P

Overwrites files three times with random patterns of data before deleting. This is useful for deleting sensitive files because it reduces the chance that they can be recovered with the W option.

-W

Attempts to undelete a file that was previously deleted with the rm command. This only works in certain circumstances, so don't depend on it.


Creating and Removing Directories

The mkdir command is used to create a directory. If you don't specify a path on the command line, mkdir will assume that the directory should be created as a subdirectory of the current directory. For example, type mkdir workdocs to create a new directory called workdocs in whatever directory you are currently in. To create a whole path of directories at once, use the -p option; for example, mkdir -p workdocs/chapters/chapter1 creates not just the chapter1 directory, but also chapters and workdocs if they don't already exist.

Use the rmdir command to remove directories. rmdir will only remove a directory if it is empty. Used with the -p option, it removes a directory and its subdirectories, provided that the subdirectories are also empty. If you need to remove directories that have files in them, use the rm -R command instead.

The touch Command

The touch command serves two primary purposes: It can be used to create an empty file, and it can be used to modify the last access or last modification time of an existing file. Its basic format is

touch filename


where filename is the name of the file you want to create or modify.

The touch command supports a few options that control how the last accessed or last modified times are set. See the man page for touch for full details.

Creating Links

As mentioned briefly earlier, you can create files or directories that are links that point to other places in the filesystem. This is useful to avoid having to type long pathnames or having to navigate through many sublevels of folders from the GUI. You can think of links as being similar to shortcuts in Windows. There are a few important differences, though, which you will look at in the following sections. The two kinds of links are hard links and soft links. Let's look at hard links first.

Hard Links

A hard link is a directory entry that points to the same inode (physical location on the hard disk) as another file. There is actually only one file, but two or more directory entries point to the same physical data on the hard disk.

By default, the ln ("link") command creates hard links. Here's an example:

# ln /home/btman/documents/books/fbsd/file1.txt ./file.txt


This creates an entry in the current directory called file1.txt that points to the same location on the hard disk as /home/btman/documents/books/fbsd/file1.txt. I can now access the same file by using either directory entry (presumably I would create a link like this so I only have to type vi file1.txt after I log in to edit this file rather than vi documents/books/fbsd/file1.txt). If I now use ls -l on this link, it will look something like the following:

-rw------- 2 btman users 26896 Mar 25 19:18 file.txt


This looks like any other plain old file, right? That's because it is a plain old normal file, for all practical purposes. The only visual cue you have that this is a link is seeing the number 2 after the permissions string. This indicates that two directory entries are pointing to this inode (physical location) on the hard disk. Any changes I make to this file or its directory entry will affect the other directory entries that point to this same location. For example, if I change the permissions on this entry, the original directory entry in /home/btman/documents/books/fbsd/file1.txt will reflect the changes as well. The modification time here reflects the same modification time as the original directory entry. The size also reflects the size of the original directory entry.

If I delete the original directory entry in /home/btman/documents/books/fbsd/file1.txt, the directory entry will be removed, and the link count will be decremented by one to show the change. However, the file still exists because there is another link pointing to that same location on the hard disk (the link you created). The file will not actually be deleted until all its hard links have been removed and the link count is decremented to zero.

Hard links have two important limitations:

  • They cannot be used to link directories.

  • They cannot cross filesystem boundaries (for example, you cannot create a link from within /usr to a location in /var).

If you need to link a directory or cross a filesystem boundary, you will have to use a soft link.

Soft Links

Soft links (also called symbolic links or symlinks) are similar from a user's perspective to shortcuts in Windows or aliases in Mac OS X. Unlike hard links, a soft link is a separate file that has its own inode on the hard disk. The soft link is simply a "stub" file that contains a pointer to another file. Use the -s option with ln to create a soft link. Here's an example:

# ln -s /home/btman/documents/books/fbsd/file1.txt file.txt


If you use ls -l on this file, it will look something like this:

[View full width]

lrwxr-xr-x 1 btman users 31 Mar 25 19:56 file.txt -> /home/btman/documents/books/fbsd /file1.txt


Notice the differences between this version and the hard link:

  • The permissions do not indicate the permissions of the target file to which the link refers. Also, you cannot change the attributes of a soft link (permissions, owner, or group). You must do this by manipulating the target file.

  • The link count is only one instead of two. This is because the soft link is an actual file that points to the other file. It is not simply a directory entry that points to a location on the hard disk (as a hard link is).

  • The file size is lying to us. The size listed here is the size of the file containing the linknot the size of the target file it points to.

  • The file modification time is also deceiving. It tells us the time the link was last modified, but it tells us nothing about the time the target file was last modified.

  • The filename tells us the name of the file that this file points to (after the -> symbol).

Also, unlike with a hard link, if you delete the original file that a soft link points to, the file's data blocks are removed and the link becomes an orphan that no longer works. However, if you delete the link with rm, the target file remains untouched.

Tip

If you are trying to access a file and you keep getting No such file or directory errors, and yet when you do an ls, the file is clearly there, you are probably trying to use a soft link that has become an orphan, meaning that its target (or parent) no longer exists. Use the -l option to ls and see whether the file is a soft link. If it is, check to see whether the file it points to actually exists. Note that deleting or even simply moving a file can cause its soft links to become orphans.


Which style of links to use is as much a matter of style as of technical best practices. You might want to use hard links if you are pointing to a file located on the same filesystem as the one you are currently on because hard links have the advantages of providing you with information about the actual files and of not becoming orphans if the original files are deleted or moved. However, if you need to link to a directory or link to a file that is located on a different filesystem, you must use soft links. It's also a lot easier to detect a soft link using ls, and they're generally more versatile and easier to understand than hard links.

Note

Hard links also have one other advantage over soft links: They don't take up an inode. This may not seem like a huge issue, but there's a fixed number of inodes available on the hard disk, and it's possible to run out of inodes if you have a lot of very small files on the disk, even if you have lots of space left on the hard disk. When you run out of inodes, no more files can be created until you have deleted some files and thus freed up some inodes.


Universal Options

Many (but not all) of the file-manipulation commands available in FreeBSD support the options shown in Table 8.7. Before using these options, though, be sure to check the man page for proper syntaxsome commands might use certain well-known option names for unusual purposes!

Table 8.7. Universal Options for Most Shell Commands

Option

Result

-i

Runs in interactive mode, prompting you before taking action on each file if that action would cause damage to an existing file.

-v

Is verbose about what the command is doing. In other words, the command prints messages on the screen for each operation it performs.

-q

Is quiet (the opposite of verbose); the command doesn't print any status messages as it runs.

-f

Forces the action without asking, even if the file permissions prohibit the action (for example, this action could be used to delete a file without asking whether the file is set to read-only, assuming that you have write privileges in the directory where the file is located).


Caution

As you may have noticed, most UNIX commands that deal with file and directory manipulation will pretty much do whatever you tell them to do without asking any questions, even if the action will destroy existing files. UNIX doesn't hold your hand like Windows or DOS does. UNIX assumes you know what you are doing when you tell it to do something. Because of this, if you aren't completely sure of what you are doing (for example, if you aren't sure whether there might be existing files of the same name in a directory you are copying another directory to), it's often a good idea to use the -i option with many of these commands. This way, you will be prompted before the command does anything that will damage existing files.


Meta-characters and Wildcard Operators

All the previously mentioned commands also support meta-characters and wildcards. These allow you to match one or more unknown characters.

Caution

DOS users: Before you get any ideas of skipping this section because you think you know all about wildcards, remember that UNIX and FreeBSD wildcards do not behave like DOS wildcards. Part of this is because the period (.) is just another character in a filename as far as UNIX is concerned. UNIX gives no special treatment to the period like DOS does. This means that although del * would do virtually nothing in DOS, rm * will delete every visible file in the current directory in UNIX! Be careful with UNIX wildcards, especially if you are used to how wildcards behave in DOS.


You can use three primary wildcard operators in FreeBSD. These wildcard operators are shown in Table 8.8.

Table 8.8. Wildcard Operators

Operator

Meaning

?

Matches any single unknown character. For example, file?.txt will match the files file1.txt, file2.txt, and fileA.txt. However, it will not match file10.txt or fileAB.txt.

*

Matches any number of unknown characters. For example, f* will match the files f, foo, file, file1.txt, file2.txt, fileA.txt, file10.txt, and fileAB.txt.

[]

Matches a range of characters. (This operator is explained in the following section because it requires more detail than can fit well in this table.)


Matching Ranges of Characters

You can match ranges of characters by enclosing them in brackets. For example, file[1-3] will match file1, file2, and file3, but not file4. This also works with characters: file[a-c] will match filea, fileb, and filec.

Tip

When dealing with ranges of characters, it is important to remember that the matching is based on the ASCII number value of the character. For example, file[A-b] will match fileA and fileb, but it will also match fileB, fileC, fileD, fileE, and so onall the way up to fileZ. This is because uppercase letters come before lowercase letters in the ASCII chart. Therefore, any time you specify an uppercase letter as the starting point for the match and a lowercase letter as the ending point, all the uppercase letters between the one you specify and the letter Z will also be matched. Refer to http://www.lookuptables.com/ for more information on ASCII values.


You can also match one of several characters simply by including them in a list. For example, file[1234]* will match any file beginning with file1, file2, file3, or file4, no matter what follows it. Notice that this example combines two wildcard operators, which is perfectly legal.

Finally, you can use the logical NOT operatoran exclamation point (!) in bash, a caret (^) in tcshwith wildcards. For example, file[!1234]* will match all files that begin with file except file1*, file2*, file3*, or file4*.

Caution

Be extremely careful when using wildcards with commands such as rm because it is easy to make disastrous mistakes. For example, suppose you accidentally type rm note * when you meant to type rm note*. The shell interprets the space as an argument separator. Therefore, this simple typo of putting a space between note and the asterisk changes this command from "remove all files beginning with note" to "remove the file note and then remove all other files in the directory!" So, double- and triple-check your typing when using wildcards with commands such as rm. (Better yet, use the -i option to force rm to prompt you for each deletion.) Also, quadruple-check when using the R (recursive) option, which can result in complete destruction of your system if used improperly.


Tip

One trick you can use when working with wildcards and potentially destructive commands is to use the wildcard with the ls command, instead of the command you're really going to use, as a harmless "dry run" before executing the final command. Then, to execute the real, potentially destructive command, simply press the Up arrow to recall the harmless ls version from your command history, and change only the command name. It pays to take all the precautions you can when it comes to avoiding dangerous typos!


Notes on Filenames

It is all right to include spaces in files, but if you do you will need to place the filenames in quotes so as to tell the shell to interpret the filename as one argument, not two separate files, or to use the backslash (\) to "escape" the space characters and force them to be interpreted literally. A common practice, and the one I recommend, is to use underscores in filenames instead of spaces. This makes them easy to read and also eliminates the need to quote filenames. Also, for similar reasons, avoid using filenames with special charactersyou'll thank yourself later if you ever need to access those files.

Caution

One serious problem with filenames that contain spaces is that they can cause you to accidentally delete files that you did not intend to delete. For example, suppose you have three files: the first is named business, the second is named letter, and a third is named business letter. Suppose you want to delete the file business letter, but you forget to quote the filename when issuing the rm command. Remember that the shell interprets a space as an argument separator unless it is quoted. Therefore, forgetting the space when issuing this command will result in the files letter and business being deleted, but the file business letter will be left untouched. This is not what you intended to happen. This is another good argument for not using spaces in filenames, although this is also a good example of a case where modern shells' filename completion features (which properly escape the spaces) can both save you time and protect you from typos.


Dealing with Funky Filenames

Most filenames in UNIX are of a simple, predictable form: alphanumeric characters, upper-and lowercase, and no spaces. However, this is just a convention; UNIX fully supports filenames that contain all kinds of special characters, including spaces, quotes, parentheses, and other odd symbols that you would normally only expect to see on Windows or Macintosh files, where command-line manipulation of filenames is unnecessary. The only character that is not allowed in UNIX filenames is the forward slash (/).

However, although most UNIX programs will only create files with well-behaved names, files that originate on Windows or Macintosh computers might end up (via FTP or other methods) on your FreeBSD machine with spaces or other unusual characters in them, and you will need to know how to deal with them.

For example, here is a directory listing that contains several files with funky names:

*             File\1.txt      file4.txt        file6.txt File 1        file"3".txt     file5.txt


These filenames are for demonstration purposes only. Don't create filenames like this in practice!

The first special case here is the file *. How can you remove this file? If you are new to UNIX, your first reaction might be simply to type rm *, which would remove a file named *, right? Well, it will certainly remove this file, but the shell interprets the asterisk as a wildcard character. Because of this, it will remove this file and also every other file in the directory! This is obviously not what you want to happen.

The shell provides an "escape" character for cases such as this one: the backslash (\). It tells the shell that it should interpret the next character in the string as a normal character instead of giving it the special treatment it might otherwise receive. In this case, then, the command rm -i \* would remove the offending file while leaving the other characters untouched.

The second problematic file is File\1.txt. In this case, the filename itself contains the escape character, the backslash. Typing rm File\1.txt will result in File1.txt: No such file or directory because you've merely told the shell to treat the character 1 as a normal characterwhich it would have done anyway. The solution here is to simply escape the escape character itself, like this:

# rm -i File\\1.txt


Next you come to the file named File 1. The shell interprets spaces as argument separators, so rm File 1 will not remove this file. Instead, this command will attempt to remove two files: one named File and the other named 1. In order to get the shell to interpret the string as a single argument, you need to quote it. In this case, rm -i "File 1" (or rm -i File\ 1) will do the trick.

So what about file"3".txt? Once again, if you simply try rm file"3".txt, you will see file3.txt: No such file or directory. This is because the shell interprets " as a special character. Once again, you need to escape it with the backslash. The command rm -i file\"3\".txt will do the trick, although being clever with quote marks (rm -i 'file"3".txt') will also work.

Tip

Notice that the -i option to rm, which prompts for confirmation before deleting the file, is used in all the previous examples. This is a good habit to get into when trying to remove files with unpredictable names. This way, you can be sure the command you are issuing will actually have the effect you intend it to have, and it won't delete some files you don't want deleted.


Where Did I Put That File Again?

It happens to all of us. Once in a while we create files or save files and then we simply can't remember where we put them. For situations such as this, FreeBSD provides the find command, which has a somewhat nonstandard syntax. Here is an example of how to use it:

# find . -name "lostfile*"


This command will find all files beginning with the name lostfile that are in the current directory or any directory within the current directory. Note that a search done from the root directory will check every subdirectory on the entire systemeven subdirectories located on other disks or across NFS mounts. This can take quite some time on large disks. There are various options to control how far into the directory hierarchy find will go, and whether it will traverse filesystems or only look on the current filesystem. You can also use find to search for files based on criteria other than name, such as the owner, group, and size. See the man find page for full details on this command.

A related command, called locate, does not actually search for the file but instead searches a database list of files on the system. Because of the database back-end, locate is many times faster than find. The drawback is that there could be files on the system that the locate database doesn't know about and won't find. Depending on the system, the locate database is usually updated once a day or sometimes once a week (you can control the frequency of the updates; see the man locate and man updatedb pages for more details).

That covers the bulk of what you need to know to manipulate files from the command line. Although this part of the chapter didn't cover all the available commands, you now know about the ones you are likely to use on a regular basis, and you know where to look for additional documentation. For more information on each of these commands and their options, see their respective man pages.




FreeBSD 6 Unleashed
FreeBSD 6 Unleashed
ISBN: 0672328755
EAN: 2147483647
Year: 2006
Pages: 355
Authors: Brian Tiemann

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net