Solaris Advanced User's Guide

Chapter 3 Working With Files and Directories

You can use the SunOS command line to work with, organize, and manage files and directories. You type the file and directory names with SunOS commands to complete specific operations. The command line operates differently than a desktop File Manager. In a File Manager, you can display files as icons that you can click on and move, and you can select commands from menus.

This chapter describes the following topics.

File Concepts

A file is the basic unit in the SunOS operating system. Almost everything is treated as a file, including the following items.

The following section explains the commands for creating, listing, copying, moving, and deleting files. This section also includes information on how to list the contents of a file and how to determine the nature of a file.

Using File Commands

Each of the command descriptions in this section includes an example of how to use the command. Try the examples as you read the text.

Before You Begin

Before you experiment with files, make sure that you are in your home directory. Your system administrator established this directory for you at your account creation. To avoid changes to parts of your system that other users expect to remain unchanged, perform the following tasks in your home directory.

To make certain that you are in your home directory, type the cd (change directory) command. This command moves you to your home (default) directory. Then type the pwd (print working directory) command to display your current location within the file system. The directory displayed is your home directory:


$ cd
$ pwd
/export/home/username

In this example, the user's home directory is /export/home/username, where username is the name of the user who owns the home directory.

Creating a Test File

Use the touch command to create an empty file.


$ touch tempfile
$ 

If a file by the name you specify does not exist, the touch command creates an empty file.


Note –

If the file already exists, touch updates the last file access time.


Listing Files (ls)

Now list the file with the ls command to verify that you've created it:


$ ls tempfile
tempfile 

When you type the ls command by itself, it lists all the files in your current location. If you type the ls command with a specific file name, it lists only that file, if the file exists.

For more information on listing files, see the man page ls(1).

Copying Files (cp)

Use the cp command to copy tempfile to a file called copyfile:


$ cp tempfile copyfile
$ 

Now list both files. Notice that both names end with the characters “file.” You can use the wildcard character, asterisk (*), to match any character or sequence of characters. The command ls *file lists both tempfile and copyfile, and any other file in this directory with a name that ends with file.


$ ls *file
copyfile    tempfile

Notice that copyfile is listed first. Files are listed in alphabetical order. Capital letters and numbers precede lowercase letters.

For detailed information on copying files, see the man page cp(1).

Moving and Renaming Files (mv)

You can move and rename files by using the same command, mv (move). In this example, use the mv command to rename tempfile to emptyfile:


$ mv tempfile emptyfile
$ 

Then list both files again to verify the change.


$ ls *file
copyfile    emptyfile

tempfile is replaced by emptyfile.

For more information on moving and renaming files, see the man page mv(1).

Deleting Files (rm)

Use the rm (remove) command to delete copyfile, and verify the result with the ls command:


$ rm copyfile
$ ls *file
emptyfile

Caution – Caution –

Be careful when you use the rm command, and be particularly careful when you use rm with the wildcard character (*). You cannot recover files that you have removed with rm.


For more information on the rm(1) command, refer to the man Pages(1): User Commands.

Displaying File Contents (more, cat)

Use the more command to display the contents of a file. Type more and follow it with the name of the file to be displayed. The contents of the file scroll down the screen. If the file is longer than one screen, this message appears:


--More--(nn%)

where nn is the percentage of the file already displayed.

You can also use the cat command to display the contents of a file, but it displays the file contents rapidly without pausing. The cat (concatenate) command is more often used to join two or more files into one large file, as in this example:


$ cat file1 file2 file3 > bigfile
$ ls *file
bigfile
file1
file2
file3
$

For further information on the more(1) or cat(1) commands, refer to the man Pages(1): User Commands.

Displaying File Type (file)

Some files, such as binary files and executable files, are not printable and cannot be displayed on the screen. Use the file command to show the file type.


$ file *
myscript:      executable shell script
print.ps:      PostScript document
save.txt:      ascii text

Directories and Hierarchy

This section describes the directory hierarchy that the Solaris operating environment uses to manage and organize files.

Directory Hierarchy

Files are grouped into directories, and directories are organized in a hierarchy. At the top of the hierarchy is the “root” directory, symbolized by “/”.

In the following example, Figure 3–1, each directory in the file system contains many subdirectories. The / character distinguishes directory levels. The directory / (root) contains the subdirectories /usr, /bin, /export/home and /lib, among others subdirectories. The subdirectory /export/home contains user1, user2, and user3.

When you initiate commands, you specify directories and files by including the names of the directories that contain the files or directories you want to work with. The names of directories and the files beneath them, combined with slash separators, constitute a path name. For example, the path name for the user3 directory in the following illustration is /export/home/user3.

Figure 3–1 File System Hierarchy

The preceding and following contexts describe the diagram.

All subdirectory names and file names within a directory must be unique. However, names within different directories can be the same. For example, the directory /usr contains the subdirectory /usr/lib. No conflict occurs between /usr/lib and /lib because the path names are different.

Path names for files work exactly like path names for directories. The path name of a file describes that file's place within the file-system hierarchy. For example, if the /export/home/user2 directory contains a file called report5, the path name for this file is /export/home/user2/report5. This example shows that the file report5 is within the directory user2, which is within the directory home, which is within the root (/) directory.

Printing the Working Directory (pwd)

The pwd command (print working directory) displays where you are in the file system hierarchy.


$ pwd
/home/user1

Your output might be different from the example, as your directory structure is different. Your working directory is your current location within the file-system hierarchy.

Your Home Directory

Every user has a home directory. When you first open a terminal or a window, your initial location is your home directory. Your system administrator creates your home directory for you at your account creation.

Changing the Working Directory (cd)

The cd (change directory) command enables you to move around within the file-system hierarchy.


$ cd /usr/lib
$ pwd
/usr/lib

When you type the cd command by itself, you return to your home directory. For example, if your home directory was /export/home/user1:


$ cd
$ pwd
/home/user1

Although your home directory is /export/home/user1, the cd command returns you to the/home/user1 because home directories are mounted on the /home directory by the automounter.

In the Bourne Again, C, Korn, TC, and Z shells, the tilde (~) is used as a shortcut for specifying your home directory. For example, you would type the following to change to the subdirectory music within your home directory:


example% cd ~/music

You can also use this shortcut to specify another user's home directory. For example:


example% cd ~username

where username is another user's login name, you would change to that user's home directory.


Note –

The Bourne shell does not support the ~ shortcut.


If you use the Bourne shell, your system administrator might have configured the system so that you can type $home to specify your home directory. With this configuration, you type the following command to change your working directory to the subdirectory music in your home directory.


$ cd $home/music

The directory immediately “above” a subdirectory is called the parent directory. In the preceding example, /home is the parent directory of /home/user1. The symbol .. (“dot-dot”) represents the parent directory. The command cd .. changes the working directory to the parent directory, as in this example:


$ pwd
/home/user1
$ cd ..
$ pwd
/home

If your current working directory is /home/user1 and you want to work with some files in /home/user2, type the following command.


$ pwd
/home/user1
$ cd ../user2
$ pwd
/home/user2

../user2 tells the system to look in the parent directory for user2. As you can see, this command is much easier than typing the entire path name /home/user2.

Creating a Directory (mkdir)

To create a new directory, type the mkdir command and follow it with the name of the new directory.


$ mkdir veggies
$ cd veggies
$ mkdir broccoli
$ cd broccoli
$ pwd
/home/user2/veggies/broccoli

Relative Path Names

The full path name of a directory or a file begins with a slash (/) and describes the entire directory structure between that file (or directory) and the root directory. However, you can often use a shorter name that defines the file or directory relative to the current working directory.

When you are in a parent directory, you can move to a subdirectory by using only the directory name and not the full path name. In the previous example, the command cd veggies uses the relative path name of the directory veggies. If the current working directory is /home/user2, the full path name of this directory is /home/user2/veggies.

Create several different subdirectories, and then move around within this directory structure. Use both full path names and relative path names, and confirm your location with the pwd command.

Moving and Renaming Directories

You rename a directory by moving it to a different name. Use the mv command to rename directories.


$ pwd
/home/user2/veggies
$ ls
broccoli
$ mv broccoli carrots
$ ls
carrots

You can also use mv to move a directory to a location within another directory.


$ pwd
/home/user2/veggies
$ ls
carrots
$ mv carrots ../veggies2
$ ls ../veggies2
carrots

In this example, the directory carrots is moved from veggies to veggies2 with the mv command.

Copying Directories

Use the cp -r command to copy directories and the files they contain:


$ cp -r veggies veggies3
$

The command in the previous example copies all files and subdirectories within the directory veggies to a new directory veggies3. This is a recursive copy, as designated by the -r option. If you attempt to copy a directory without using this option, the system displays an error message.

Removing Directories (rmdir)

To remove an empty directory, use the rmdir command as follows:


$ rmdir veggies3
$ 

If the directory still contains files or subdirectories, the rmdir command does not remove the directory.

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r.


$ rm -r veggies3
$

Caution – Caution –

Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


Viewing Differences Between Files (diff)

Use the diff command to view differences between similar files. The following command scans each line in leftfile and rightfile to check for differences.


$ diff leftfile rightfile

When the diff utility finds a line or lines that differ, diff determines if the difference is the result of an addition, a deletion, or a change to the line, and how many lines are affected. diff tells you the respective line number or numbers in each file, followed by the relevant text from each file.

If the difference is the result of an addition, diff displays a line with the following format.


   
l[,l] a r[,r]

In the previous example, l is a line number in leftfile and r is a line number in rightfile.

If the difference is the result of a deletion, diff uses a d in place of a. If the difference is the result of a change on the line, diff uses a c.

The relevant text from both files immediately follow the line number information. Text from leftfile is preceded by a left angle bracket (<). Text from rightfile is preceded by a right angle bracket (>).

This example shows two sample files, followed by their diff output.


$ cat sched.7.15
Week of 7/15

Day:  Time:        Action Item:          Details:

T     10:00        Hardware mtg.         every other week
W     1:30         Software mtg.
T     3:00         Docs. mtg.
F     1:00         Interview
$ cat sched.7.22
Week of 7/22

Day:  Time:        Action Item:          Details:

M     8:30         Staff mtg.            all day
T     10:00        Hardware mtg.         every other week
W     1:30         Software mtg.
T     3:00         Docs. mtg.
$ diff sched.7.15 sched.7.22
1c1
< Week of 7/15
---
> Week of 7/22
4a5
> M     8:30         Staff mtg.            all day
8d8
< F     1:00         Interview

If the two files to be compared are identical, diff does not display output.

For more information on the diff(1) command, refer to the man Pages(1): User Commands.

Comparing Three Different Files (diff3)

To compare three different versions of a file, use the diff3 command.


$ diff3 file1 file2 file3

diff3 compares three versions of a file and publishes the differing ranges of text that are flagged with these codes:

==== all three files differ

====1 file1 is different

====2 file2 is different

====3 file3 is different

Using bdiff on Large Files

If you are comparing large files, use bdiff instead of diff. Use the diff command syntax with bdiff.


$ bdiff leftfile rightfile

Use bdiff instead of diff for files longer than 3500 lines.

Searching for Files (find)

The find command searches for files that meet conditions you specify, starting from a directory you name. For example, you might search for file names that match a certain pattern or that have been modified within a specified time frame.

Unlike most commands, find options are several characters long. You must specify the starting directory before your desired options.


$ find directory options

In the previous example, directory is the name of the starting directory and options represents the options for the find command.

Each option describes a criterion for selecting a file. A file must meet all criteria to be selected. The more options you apply, the narrower the field becomes. The -print option indicates that you want the system to display the results.

The -name filename option tells find to select files that match filename. Here filename is taken to be the rightmost component of a file's full path name. For example, the rightmost component of the file /usr/bin/calendar is calendar. This portion of a file's name is often called the base name.

For example, to see which files within the current directory and its subdirectories end in s, type the following command.


$ find . -name '*s' -print
./programs
./programs/graphics
./programs/graphics/gks
./src/gks
$

The following table describes other options of the find command.

Table 3–1 find Options

Option 

Description 

-name filename

Selects files with a rightmost component that matches filename. Surround filename with single quotes if it includes filename substitution patterns.

-user userid

Selects files that are owned by userid. userid can be either a login name or user ID number.

-group group

Selects files that belong to group.

-m -time n

Selects files that have been modified within n days.

-newer checkfile

Selects files that have been modified more recently than checkfile.

 

You can specify an order of options by combining options within escaped parentheses (for example, \(options\) ). Within escaped parentheses, you can use the -o flag between options to indicate that find should select files that qualify under either category, rather than just those files that qualify under both categories.


$ find . \( -name AAA -o -name BBB \) -print
./AAA
./BBB

In the previous example, the find command searches in the . directory for all files that are named AAA, then looks for all files named BBB. find then displays the results of both searches.

You can invert the sense of an option by including an escaped exclamation point before the option. find then selects files for which the option does not apply:


$ find . \!-name BBB -print
./AAA

You can also use find to apply commands to the files it selects with the following options.

-exec command '{}' \;

You terminate this option with an escaped semicolon (\;). The quoted braces are replaced with the file names that find selects.

You can use find to automatically remove temporary work files. If you name your temporary files consistently, you can use find to search for and remove these files. For example, if you name your temporary files junk or dummy, this command finds and removes the files.


$ find . \( -name junk -o -name dummy \) -exec rm '{}' \;

For more information on searching for files, see the man page find(1).

File and Directory Security

File permissions help to protect files and directories from unauthorized reading and writing. Often you will have files you want to allow others to read but not change. In other situations, you might want to share executable files or programs. File permissions enable you to control access to your files.

The following list describes the three basic file and directory permission types.

You can set permissions for three categories of users.

Displaying Permissions and Status (ls -l)

Use the -l with the ls command to display a long listing of files and directories in alphabetical order.

Figure 3–2 Displaying Permissions and Status

The following context describes the screen output.

The first character on the line indicates the file type. A dash (-) indicates an ordinary file, a d indicates a directory, and other characters can indicate other special file types.

The next nine characters indicate the permissions for the file or directory. The nine characters consist of three groups of three, showing the permissions for the owner, the owner's group, and the world, respectively. The permissions for emptyfile are rw-r--r--, indicating that the owner can read and write this file, everyone can read it, and no one can execute it. The permissions for the directory veggies2 are rwxr-xr-x, indicating that everyone has read and execute permissions, but only the owner can write to it.

In addition to file permissions, the display shows the following information:

When you give the name of a directory, the ls -l command prints information on all the files and directories in that directory.

Listing Hidden Files (ls -a)

Some files are not listed by the ls command. These files have names that begin with the character . (called “dot”), such as .cshrc, .login and .profile. Use the ls -a command to list these dot files:


$ ls -a
.
..
.cshrc
.login
.profile
emptyfile

Notice that the files beginning with . are listed before the other files. The file . is the reference for the current directory, and the file .. is the reference for the parent directory.

In general, system utilities use files that begin with . and the user cannot modify these files. Some exceptions to this rule do exist.

Changing Permissions (chmod)

Use the chmod command to change permissions for a file or directory. You must be the owner of a file or directory, or have root access, to change its permissions. The general form of the chmod command is:


chmod permissions name

In this example, permissions indicates the permissions to be changed and name is the name of the affected file or directory.

You can specify the permissions in several ways. Here is one of the forms that is easy to use:

  1. Use one or more letters to indicate the type of users.

    • u (for the user)

    • g (for group)

    • o (for others)

    • a (for all three of the previous categories.))

  2. Indicate whether the permissions are to be added (+) or removed (-).

  3. Use one or more letters to indicate the permissions.

    • r (for read)

    • w (for write)

    • x (for execute)

In the following example, write permission is added to the directory carrots for users who belong to the same group (thus, permissions is g+w and name is carrots).


$ cd veggies2
$ ls -l
drwxr-xr-x   2 user2    users        512 Nov  1 09:11 carrots
$ chmod g+w carrots
$ ls -l
drwxrwxr-x   2 user2    users        512 Nov  1 09:11 carrots
$

The chmod g+w carrots command in the previous example gives the group write permission on the file carrots. The hyphen (-) in the set of permissions for group is changed to a w.

To make this same directory unreadable and unexecutable by other users outside your group type the following commands.


$ ls -l
drwxrwxr-x   2 user2    users        512 Nov  1 09:11 carrots
$ chmod o-rx carrots
$ ls -l
drwxrwx---   2 user2    users        512 Nov  1 09:11 carrots
$

Now, the r (for read) and the x (for execute) in the set of permissions for other users are both changed to hyphens (-).

When you create a new file, the system automatically assigns the following permissions.

-rw-r--r--

When you create a new directory, the system automatically assigns the following permissions.

drwxr-xr-x

For example, to make a new file turnip executable by its owner (user2), type the following command.


$ ls -l turnip
-rw-r--r--   1 user2    users        124 Nov  1 09:14 turnip
$ chmod u+x turnip
$ ls -l turnip
-rwxr--r--   1 user2    users        124 Nov  1 09:14 turnip
$

If you want to change permissions for all categories of users, use the -a option of the ls command. To make a new file garlic executable by everyone, type the following command.


$ ls -l garlic
-rw-r--r--   1 user2    users        704 Nov  1 09:16 garlic
$ chmod a+x garlic
$ ls -l garlic
-rwxr-xr-x   1 user2    users        704 Nov  1 09:16 garlic
$

The x in the output of the ls -l command indicates garlic is executable by everyone.

You can also use the * wildcard character to change permissions for groups of files and directories. For example, to change the permissions for all the files in the current directory veggies so that the files can be written by you alone, type the following command.


$ pwd
/home/user2/veggies
$ ls -l
-rwxrwxrwx   1 user2    users       5618 Nov  1 09:18 beets
-rwxrwxrwx   1 user2    users       1777 Nov  1 09:18 corn
-rwxrwxrwx   1 user2    users       3424 Nov  1 09:18 garlic
-rwxrwxrwx   1 user2    users      65536 Nov  1 09:18 onions
$ chmod go-w *
$ ls -l
total 152
-rwxr-xr-x   1 user2    users       5618 Nov  1 09:18 beets
-rwxr-xr-x   1 user2    users       1777 Nov  1 09:18 corn
-rwxr-xr-x   1 user2    users       3424 Nov  1 09:18 garlic
-rwxr-xr-x   1 user2    users      65536 Nov  1 09:18 onions
$

Note –

Perform this chmod operation on the current directory only.


Setting Absolute Permissions

In the previous section, you used the chmod command to change file permissions relative to their current settings. You can also set the permissions for a file or directory absolutely by using numeric codes with the chmod command.

The syntax for this usage of the chmod command is:

chmod numcode name

In this example, numcode is the numeric code and name is the name of the file or directory for which you are changing permissions.

The complete numeric code consists of three numbers. One number is used for each of the three categories: user, group, and others. For example, the following command sets absolute read, write, and execute permissions for the user and the group, and execute permissions only for others.


$ chmod 771 garlic

Table 3–2 illustrates how the the code 771 describes the permissions for garlic.

Table 3–2 Permissions for garlic

Permission 

User 

Group 

Others 

Read 

Write 

Execute 

Total 

Each of the columns in Table 3–2 represents one of the categories: user, group, and others. To set read permissions, add 4 to the appropriate column. To set write permissions, add 2. To add execute permissions, add 1. The total in all three columns in the last row of the table is the complete numeric code.

The following is another example of using numeric codes to set absolute permissions, with the inclusion of the ls -l command to demonstrate the results.


$ ls -l onions
-rwxr-xr-x   1 user2    users      65536 Nov  1 09:18 onions
$ chmod 755 onions
$ ls -l onions
-rwxr-xr-x   1 user2    users      65536 Nov  1 09:18 onions
$

The chmod 755 onions command sets the permissions for the file onions so that the user can read, write, and execute, group members can read and execute, and others can read and execute. Table 3–3 describes the numeric code that is used to set the permissions for onions.

Table 3–3 Permissions for onions

Permission 

User 

Group 

Others 

Read 

Write 

Execute 

Total 

To provide read, write, and execute permissions for the file cabbage to yourself, your group, and all other users, type the following command.


$ ls -l cabbage
-rw-r--r--   1 user2    users         75 Nov  1 09:28 cabbage
$ chmod 777 cabbage
$ ls -l cabbage
-rwxrwxrwx   1 user2    users         75 Nov  1 09:28 cabbage
$

Table 3–4 describes the numeric code that is used to set permissions in the previous example.

Table 3–4 Permissions for cabbage

Permission 

User 

Group 

Others 

Read 

Write 

Execute 

Total 

The numeric code 777 represents the maximum level of permissions you can provide.

Similar to changing relative permissions, you can also use the wildcard character * to set absolute permissions for all in the files in the current directory. For example, suppose you want to set absolute permissions for all files in the current directory as follows:

To set these permissions, type the following commands.


$ pwd
/home/user2/veggies
$ ls -l
-rwxrwxrwx   1 user2    users       5618 Nov  1 09:18 beets
-rwxrwxrwx   1 user2    users       1777 Nov  1 09:18 corn
-rwxrwxrwx   1 user2    users       3424 Nov  1 09:18 garlic
-rwxrwxrwx   1 user2    users      65536 Nov  1 09:18 onions
$ chmod 751 *
$ ls -l
-rwxr-x--x   1 user2    users       5618 Nov  1 09:18 beets
-rwxr-x--x   1 user2    users       1777 Nov  1 09:18 corn
-rwxr-x--x   1 user2    users       3424 Nov  1 09:18 garlic
-rwxr-x--x   1 user2    users      65536 Nov  1 09:18 onions
$

The pwd command is included in this example to illustrate that the directory on which you perform this operation must be the current directory. The ls -l command is shown only to illustrate the changes in permissions. When setting absolute permissions, you do not need to know what the permissions are currently.

For more information on the chmod(1) command, refer to the man Pages(1): User Commands.