0% found this document useful (0 votes)
55 views

Introduction To Unix Operating System Accessing Files and Directories

This document provides an overview of accessing files and directories in Unix-like operating systems. It discusses file system hierarchies and path names, both absolute and relative. Key commands covered for navigating and viewing directory contents include cd, pwd, and ls, including options for ls to view hidden files, file types, and a long listing with detailed metadata. The document also introduces concepts like soft and hard links.

Uploaded by

Michael_Swans
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Introduction To Unix Operating System Accessing Files and Directories

This document provides an overview of accessing files and directories in Unix-like operating systems. It discusses file system hierarchies and path names, both absolute and relative. Key commands covered for navigating and viewing directory contents include cd, pwd, and ls, including options for ls to view hidden files, file types, and a long listing with detailed metadata. The document also introduces concepts like soft and hard links.

Uploaded by

Michael_Swans
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Part 2.

Accessing files and directories

Part 2. Accessing files and directories


1. Objectives
Demonstrate the difference between absolute and relative path names Access files and directories within the directory tree using absolute and relative path names Use path name abbreviations to access files and directories within the directory tree List the contents of directories and determine file types Identify various shell metacharacters to abbreviate file names and path names Determine file types with the file command Display the contents of text files using the cat, more, pg, head, an tail commands Determine character, word, and line counts using the wc command Create empty files or update modification times on existing files using the touch command Use the tee command to create text within a file Create and remove directories using the mkdir and rmdir commands Manage files and directories using the mv, cp, and rm commands

2. Unix file hierarchy


2.1 Directory hierarchy
You can visualize the Unix file system as an upside down tree. At the very top of the tree is the root directory, named "/". This special directory is maintained by the Unix system administrator. Under the root directory, subdirectories organize the files and subdirectories on the system. The names of these subdirectories might be any name at all. Here is a tree diagram of a typical Unix system.

[1]. The Filesystem Hierarchy Standard (FHS) defines the main directories and their contents in Linux operating systems. Filesystem Hierarchy Standard This standard consists of a set of requirements and guidelines for file and directory placement under UNIXlike operating systems. The guidelines are intended to support interoperability of applications, system administration tools, development tools, and scripts as well as greater uniformity of documentation for these systems. "Static" files include binaries, libraries, documentation files and other files that do not change without system administrator intervention. "Variable" files are files that are not static. The Single UNIX Specification (SUS) is the collective name of a family of standards for computer operating systems to qualify for the name

Part 2. Accessing files and directories

"Unix". The SUS is developed and maintained by the Austin Group, based on earlier work by the IEEE and The Open Group. SUSv3 totals some 3700 pages, which are thematically divided into four main parts: Base Definitions (XBD) - a list of definitions and conventions used in the specifications and a list of C header files which must be provided by compliant systems. 84 header files in total are provided. Shell and Utilities (XCU) - a list of utilities and a description of the shell, sh. 160 utilities in total are specified. System Interfaces (XSH) - contains the specification of various functions which are implemented as system calls or library functions. 1123 system interfaces in total are specified. Rationale (XRAT) - the explanation behind the standard. The standard user command line and scripting interface is the POSIX shell, an extension of the Bourne Shell based on an early version of the Korn Shell. Other user-level programs, services and utilities include awk, echo, ed, vi, and hundreds of others. Required program-level services include basic I/O (file, terminal, and network) services. A test suite accompanies the standard. It is called PCTS or the POSIX Certification Test Suite. Additionally, SUS includes CURSES (XCURSES) specification, which specifies 372 functions and 3 header files. All in all, SUSv3 specifies 1742 interfaces. Note that a system need not include source code derived in any way from AT&T Unix to meet the specification. For instance, IBM OS/390, now z/OS, qualifies as a "Unix" despite having no code in common.[citation needed] There are two official marks for conforming systems UNIX 98 - the mark for systems conforming to version 2 of the SUS (partial compliance) UNIX 03 - the mark for systems conforming to version 3 of the SUS (full compliance)

Example 2.1 Listing resources


1. Start Putty and login 2. ls / The command lists the top of directory tree: a dev lib media opt sbin srv users1 users4

bin etc lib64

misc proc scratch sys users2 usr root selinux tmp users3 var

boot home lost+found mnt 3. exit

2.2 Path name


A path name uniquely identifies a particular file or directory by specifying its location in the directory tree. Path names are similar to road maps, which show how to get from one place in the directory tree to another. The slashes (/) within a path name are delimiters between object names. An object name can be a directory name or a file name. The slash at the start of a path name always represents the root directory; for example: /export/home/kirsirat/unix/lesson1 kirsirat is the parent directory of unix because directory named unix is located in the directory named kirsirat. Note - Depending on the system setup, your home directory can be located in either the /home directory or the /export/home directory or what? In Unix, a user will be automatically placed into their home directory upon login.

Part 2. Accessing files and directories

2.2 Absolute path names


A full path or absolute path is a path that points to the same location on one file system regardless of the working directory or combined paths. In Unix system it is written in reference to a root directory. Start with a slash (/) representing the root directory and then list each directory along the path to the final destination (which may be a file name or another directory). A slash (/) separates multiple directory or file names.

2.3 Relative path names


A relative path name describes the location of a directory or a file as it relates to the current working directory. A relative path name never begins with a slash (/) character. However, it does use slashes (/) within the path name as delimiters between object names (for example, directory name or file name). If you are in a directory and you want to move down to access another directory in the hierarchy, you do not have to enter an absolute path name. Simply enter the path starting with the name of the next directory down in the tree structure. Path name abbreviations are used as a quick method for moving to or referring to directories on the command line: The ~user shorthand variable refers to a user's home directory (allowing the user to navigate to it from anywhere else in the file system or use it in other Unix commands). The ~ (tilde character) shorthand command refers to that particular users home directory. Two dots ("..") point upwards in the hierarchy, to indicate the parent directory one dot (".") represents the current directory itself.

Example 2.2 Navigating Directory tree


1. Start Putty and login 2. cd .. Move to the parent directory of your home directory. 3. ls 4. cd ~/public_html Move to your home page directory. 5. cd .. Move back to your home directoy. 6. mkdir courses Make directory courses under your home directory. 7. mkdir ./courses/unixbasic Make directory unixbasic under ~/courses directory. 8. exit

2.4 File and Directory Naming Conventions


When creating files and directories, you must use the following conventions: Directory and file names can be up to 255 characters in length. The characters can be alphanumeric, and non-alphanumeric, such as underscores (_), periods (.), and hyphens (-).

Part 2. Accessing files and directories

Special characters, such as asterisks (*), ampersands (&), pipes ( | ), quotes ( ), and dollar signs ( $ ) should not be used. These particular characters hold special meaning to the shell. Spaces should not be used in directory or file names. File and directory names, as a rule, do not contain extensions. However, if desired, extensions can be used.

3. More basic commands


3.1 Changing Directories

cd (Change Directory)
At any given time, you are located in a current working directory within the directory tree. When you initially log in to the system, the current directory is set to your home directory. You can change your current working directory at any time by using the cd command if you have rights to access the directory you want to change to. You can give the target directory path in absolute or relative form. To directory directly under working directory you don't need to use path. You can always return to your own home directory by typing the cd command without an argument.

3.2 Displaying the current Directory

pdw (Print Working Directory)


The pwd command identifies the directory in which you are currently working and displays the absolute path name of the current working directory.

3.3 Displaying the Contents of a Directory

ls (LiSt directory contents)


To display the contents of a directory, use the is command. This command lists the files and directories within the specified directory. Using the ls command with no argument simply displays the contents of the current directory. Command Format ls [ -options ] pathname ...

3.3.1 Displaying Hidden Files


File names that begin with a period (.) are called hidden files. Hidden files are frequently used to customize your work environment. Use ls -a to list all files in a directory, including any hidden (.) files.

$ ls -a
3.3.2 Displaying File Types
Use ls -F to display file types. File Type Symbol

Part 2. Accessing files and directories

Directory Executable Plain text file/ASCii Symbolic link (none)

/ * @

$ ls -F
Desktop/ Documents/ Ubuntu-App@ firstfile Music/ Public/ Templates/ Note - A symbolic link is a special type of file that points to another file or directory. A symbolic link file contains the path name of the file or directory to which it points.(later more)

3.3.3 Displaying a Long Listing


To see detailed information about the contents of a directory, use the ls -l command.

$ ls -l -rw-r----- 1 ramesh team-dev 9275204 Jun 13 15:27 mthesaur.txt.gz


1st Character File Type: First character specifies the type of the file. In the example above the hyphen (-) in the 1st character indicates that this is a normal file. Following are the possible file type options in the 1st character of the ls -l output. Field Explanation - normal file d directory s socket file l link file Field 1 File Permissions: Next 9 character specifies the files permission. Each 3 characters refers to the read, write, execute permissions for user, group and world In this example, -rw-r indicates read-write permission for user, read permission for group, and no permission for others. Field 2 Number of links: Second field specifies the number of links for that file. In this example, 1 indicates only one link to this file. Field 3 Owner: Third field specifies owner of the file. In this example, this file is owned by username ramesh. Field 4 Group: Fourth field specifies the group of the file. In this example, this file belongs to team-dev group. Field 5 Size: Fifth field specifies the size of file. In this example, 9275204 indicates the file size. Field 6 Last modified date & time: Sixth field specifies the date and time of the last modification of the file. In this example, Jun 13 15:27 specifies the last modification time of the file. Field 7 File name: The last field is the name of the file. In this example, the file name is mthesaur.txt.gz. [2]

3.3.4 Listing Individual Directories


Use ls - ld to display detailed information for the directory only, not its contents.

$ ls -ld /etc drwxr-xr-x 21 root root 4096 Jun 15 07:02 /etc


3.3.5 Display Files Recursively

Part 2. Accessing files and directories

This is also known as a recursive listing. When you do this from /, it shows all the unhidden files in the whole file system recursively.

$ ls R path_name
3.3.4 Order Files Based on Last Modified Time
To display a listing sorted by the file's last modification time, with the latest modified file appearing first in the list, execute the following:

$ ls -lt
To display a listing showing the latest file modification time in reverse order, execute the following:

$ls -ltr $ls -ltr

4. Shell Metacharacters
Shell metacharacters are specific characters, generally symbols, used to represent a special meaning to the shell. Some examples of shell metacharacters include: ~ - + * ? [] ~tilde, - dash,

4.1 Using the Tilde (~) Character


The shell substitutes the tilde (~) character with the home directory of the current user. It is an abbreviation of the absolute path name; for example: Note - The tilde (~) character is available in all shells except the Bourne shell.

4.1.1 Using ~username


Attaching a user name to the tilde (~) character refers to the home directory of the specified user.

4.1.2 Using ~+ and ~The tilde and plus string refers to the current working directory. The tilde and dash string refers to the previous working directory.

4.1.3 Using the Dash


To switch quickly between two specific directories, use the Korn shell dash (-) symbol. The Korn shell automatically displays the current directory path with this particular option.

4.2 Using the Asterisk


The asterisk (*) represents zero or more characters, excluding the leading period (.) on a hidden file. The asterisk is often referred to as a wildcard character.

4.3 Using the Question Mark


The question mark (?) matches any single character, excluding the leading period (.) on a hidden file.

Part 2. Accessing files and directories

4.4 Using the Square Brackets


Use square brackets to match a set or range of characters for a single character position. When looking for a set of characters, the characters inside the brackets do not generally need to be in any order; for example, [abc] is the same as [cab]. However, when looking for a range of characters, they must be in proper order; for example, [a-z] or [0-9].

Note - You should not use these metacharacters when creating file and directory names. These particular characters hold special meaning to the shell.

Example 4.1 Special characters


1. Start Putty and login 2. ls ~kirsirat/public_html List contents of teachers home page directory. 3. mkdir courses/unixbasic/lesson2 4. cd courses/unixbasic/lesson2 Use arrow up to edit previous command and change to just created directory. 5. touch file1 file2 file3 file4 Make empty files. 6. touch tmp1 tmp2 tmp3 tmp4 Make empty files. 7. ls f* Display list of all files beginning with character f. 8. ls tmp? Display list of all files having tmp and one other character in their name. 9. ls *[2-3] 10. ls [fe]* 11. exit

5. File and directory commands


5.1 Determining File Types
There are many different file types found in the UNIX Operating Environment. Using the file command shows you to determine some file types easily. This information is important when you want to open or read a file. Knowing the file type helps you decide which command or program you need to use.

file filename(s)
The output from the file command is most often one of the following:

Part 2. Accessing files and directories

- Text - Examples include ASCII text, English text, commands text, and executable shell scripts. - Data - Data files are those that are created by an application. - Executable or binary - This file type indicates that the file is a command or program.

5.2 Creating Directories


To create a directory in Unix systems the mkdir (make directory) command is used. mkdir example Creates a directory called example in the working directory mkdir ~/dir1 Creates a subdirectory named dir1 mkdir laku paku haku Creates subdirectories laku, paku and haku mkdir .hidden Creates a directory named .hidden (which cannot be seen with issuing command ls, because directory's name starts with dot)

5.2 Copying Files and Directories


To copy one or more files or directories, you use the cp (copy) command. You might want to make a backup of a file before editing it or just make a copy from friend's directory to your own. The copy is completely independent of the original. cp filel file2 Makes a copy of filel to file2 cp directoryl/filel directory2/file2 Makes a copy of filel to file2 from directory1 into directory2. cp directoryl/filel directory2 Makes a copy of filel from directory1 into directory2 (retaining the same name) cp directoryl/filel file2 Makes a copy of filel from directory1 to current directory with namefile2 cp -r directoryl directory2 Makes a copy of directoryl, including subdirectories and files, under directory2.

5.3 Moving and Renaming of Files and Directories


Moving files and directories is completed in Unix with mv (move and rename files or directories). In Dos and Windows (at command prompt) you have the rename command for renaming files and directories. There is not an equivalent in Unix; renaming is also done by using mv.

mv file1 file2 Renames file1 to file2 mv directoryl directory2 If directory2 doesn't exist, directoryl will be renamed to directorv2. If directory2 exists, directory1 will be moved to a subdirectory under directory2. mv directoryl/filel directory2/file2 Moves filel from directory1 to directory2 renaming it to file2

Part 2. Accessing files and directories

mv directoryl/filel file2 Moves filel from directory1 to working directory named file2. mv directoryl/.filel directory2 Moves .file1 from directory1 to directory2 retaining the same name

5.4 Deleting Files and Directories


You can delete files and directories in Unix using rmdir (remove empty directories) and rm (remove files or directories). In Dos and Windows the equivalent commands are del, deltree, rmdir and rd. rmdir directory Removes directory, if the directory is empty. You cannot remove a directory that has files or directories within using rmdir. rm file Removes file rm directoryl/filel direciory2/file2 Removes file1 from directory1 and file2 from directory2. rm -r directory Removes directory recursively (removing all the files and subdirectories inside it also). rm -rf directory Removes directory and all its subdirectories and files immediately without waiting for confirmation.

6. Peak ahead: Coding in Linux


Example 6.1 Hello World
1. Start Putty and login 3. cd courses/unixbasic/lesson2 4. mkdir hello 5. cd hello 6. nano hello.hpp #ifndef HELLO_HPP #define HELLO_HPP class Hello { public: Hello(void); ~Hello(void); void print(void); }; #endif 7. nano hello.cpp #include <iostream> #include hello.hpp

Part 2. Accessing files and directories

1 0

Hello::Hello(void) /*! @brief Empty constructor for class Hello. @return None **/ { //! Write implementation if needed } Hello::~Hello(void) /*! @brief Empty destructor for class Hello. @return None **/ { //! Write implementation if needed } void Hello::print(void) /*! @brief Prints out the welcome message. @param None @return None **/ { std::cout << "Hello, world!\n"; }

8. nano engine.cpp #include hello.hpp int main () { Hello Hello1; Hello1.print(); return 0; } 9. ls engine.cpp hello.cpp hello.hpp 10. g++ -Wall engine.cpp hello.cpp -o hello 11. ls engine.cpp hello hello.cpp hello.hpp 12. ./hello Hello, world! 13. exit

7. References
[1] http://www.december.com/unix/tutor/filesystem.html (8.10.2010) [2] http://www.thegeekstuff.com/2009/07/linux-ls-command-examples/ (8.10.2010)

Part 2. Accessing files and directories

1 1

8. Links
Bash alias man page http://ss64.com/bash/alias.html Introduction to GCC http://www.network-theory.co.uk/docs/gccintro/gccintro_54.html

You might also like