Working with Files and Directories

Working with Files and Directories is very basic thing which we dont want to miss while learning Solaris 10. Lets check few very basic commands.

To display the current working directory:

pwd command: It displays the current working directory.
example:
#pwd
/export/home/ravi

To display contents of a  directory:

ls command (Listing Command):It displays all files and directories under the specified directory. 
Syntax: ls -options <DirName>|<FileName>
The options are discussed as follows:

Option
Description
pIt lists all the files & directories. The directory names are succeeded by the symbol '/'  
FIt lists all files along with their type. The symbols '/', '*', (None), '@' at the end of file name represents directory, executable, Plain text or ASCII file & symbolic link respectively
aIt lists all the files & directories name including hidden files
lIt lists detailed information about files & directories
tIt displays all the files & directories in descending order of their modified time. 
rIt displays all the files & directories in reverse alphabetical order
RIt displays all the files & directories & sub-directories in recursive order
iIt displays the inode number of  files & directories
trIt displays all the files & directories in the ascending order of their last modified date

Analysis of output of ls -l command:

ls -l → It list all the files and directories long list with the permission and other information. The output looks as follows:

FileType & Permissions LinkCount UID GID Size Last ModifiedDate & ModifiedTime <File/Directory Name>

Following table explains the output:
Entry
Description
FileType '-' for file & 'd' for directory
Permissions Permissions are in order of Owner, Group & Other
LinkCount  Number of links to the file
UID  Owner's User ID
GID  Group's ID
Size  Size of the file/directory
Last ModifiedDate & ModifiedTime Last Modified Date & Time of the file/directory 
<File/Directory Name> File/Directory name



Example:

# ls -l
total 6
-rw-r--r--   1 root     root        136 May  6  2010 local.cshrc
-rw-r--r--   1 root     root        167 May  6  2010 local.login
-rw-r--r--   1 root     root        184 May  6  2010 local.profile


Understanding permissions:
Following table explains the permission entry:

Entry
Description
-No permission/denied
rread permission
wwrite permission
xexecute permission


File Command: It is used to determine the file type. The output of file command can be "text", "data" or "binary".
Syntax: file <file name>
Example: 

# file data
data: English text

Changing Directories: 'cd' commad is used to change directories.Syntax: cd <dir name>
If cd command is used without any option it changes the directory from current working directory to user's home directory.


Example: Let the user be 'ravi' and current working directory is /var/adm/messages

#pwd
/var/adm/messages
#cd
#pwd
#/export/home/ravi


There is also a different way to navigate to the user's home directory :
#pwd
/var/adm/messages
#cd ~ravi
#pwd
/export/home/ravi
#cd ~raju
#pwd
/export/home/raju
#cd ~ravi/dir1
#pwd
/export/home/ravi/dir1

In the above examples, the '~' character is the abbreviation that represents the absolute path of the user's home directory. However this functionality is not available in all shells.

There are few other path name abbreviations which we can use as well. These are listed below :
.  → current working directory
.. → Parent directory or directory above the current working  directory.

So if we want to go to the parent directory of the current working directory following command is used:
#cd ..


We can also navigate multiple levels up in directory using cd, .. and /.
Example: If you want to move two levels up the current working directory, we will use the command : 

#cd ../..
#pwd
/export/home/ravi
#cd ../..
#pwd
/export
#cd ..
#pwd
/

Viewing the files

cat command: It displays the entire content of the file without pausing. 

Syntax: cat <file name>
Example:
#file data
data: English text
#cat data
This is an example for demonstrating the cat command.
#
Warning: The cat command should not be used to open a binary file as it will freeze the terminal window and it has to be closed. So check the file type using 'file' command, if you are not sure about it.


more command: It is used to view the content of a long text file in the manner of one screen at a time. 

Syntax: more <file name>

The few scrolling options used with more command are as follows :

Scrolling Keys
Action
Space BarMoves forward one screen
ReturnScrolls one line at a time 
bMoves back one screen
hDisplays a help menu of features 
/stringsearches forward for a pattern
nfinds the next occurrence of the pattern 
qquits and returns to shell prompt


Head and Tail command in UNIX/LINUX/SOLARIS:
head command: It displays the first 10 lines of a file by default. The number of lines to be displayed can be changed using the option -n. The syntax for the head command is as follows:
Syntax: head -n <file name>
This displays the first n lines of the file.


tail command: It displays the last 10 lines of a file by default. The number of lines to be displayed can be changed using the options -n or +n. 

Syntax: 
#tail -n <file name>
#tail +n <file name>

The -n option displays the n lines from the end of the file. 
The +n option displays the file from line n to the end of the file.  

Displaying line, word and character count:

wc command: It is used to display the number of lines, words and characters in a given file.
Syntax: wc -options <file name>
The following option can be used with wc command:
Option
Description
lCounts number of lines
wCounts number of words
mCounts number of characters
cCounts number of bytes

Example: 
#cat data
This is an example for demonstrating the cat command.
#wc -w data
9

Copying Files: 

cp command: It can be used to copy file/files. 
Syntax:cp -option(s) surce(s) destination

The options for the cp command are discussed below :
Option
Description
iPrevents the accidental overwriting of existing files or directories
rIncludes the contents of a directory, including the contents of all sub-directories, when you copy a directory

Example: 
#cp file1 file2 dir1
In the above example file1 and file2 are copies to dir1.

Moving & renaming files and directories: 

mv command: It can be used to

1. Move files and directories within the directory hierarchy :
Example: We want to move file1 and file2 under the directory /export/home/ravi to /var
#pwd
/export/home/ravi
#mv file1 file2 /var

2. Rename existing files and directories.
Example: we want to rename file1 under /export/home/ravi to file2.
#pwd
/export/home/ravi
#mv file1 file2

The mv command does not affect the contents of the files or directories being moved or renamed.

We can use -i option with the mv command to prevent the accidental overwriting of the file.

Creating files and directories :

touch Command : It is used to create an empty file. We can create multiple file using this command.
Syntax: touch <files name>
Example: #touch file1 files2 file3

mkdir command : It is used to create directories. 

Syntax: mkdir -option <dir name>

When the <dir name> includes a pah name, option -p is used to create all non-existing parent directory.

Example: 
#mkdir -p /export/home/ravi/test/test1

Removing Files and Directories :

rm command: It is used permanently remove files/directories. The Syntax:rm -option <file name>/<dir name>

The -i option is used to prompt user for confirmation before the deletion of files/directories.

Example: We want to remove file1 and file2 from the home directory of user ravi.
#pwd
/
#cd ~ravi
#pwd
/export/home/ravi
#rm file1 file2

Note: The removal of a directory is slightly different. If the directory is not empty and you are trying to delete it, you will not be able to do so. You need to use -r option to remove the directory with files and sub-directories.
Example: We want to delete a directory test under user ravi home directory and it contains file and sub-directories.
#pwd
/export/home/ravi
#rm test
rm: test is a directory
#rm -r test
#

To remove an empty directory:

Syntax: rmdir <directory name>

Links (Soft Link and Hard Link) : This section has been covered under section :Solaris File System. Please refer to it. 

Searching Files, Directories & its contents:

Using the grep command : The grep is very useful and widely used command.

lets take an example where we want to see if the process statd is running of not. Following command is used :
#ps -ef | grep statd

# ps -ef | grep statd
  daemon  2557     1   0   Jul 07 ?           0:00 /usr/lib/nfs/statd
    root 10649  1795   0 05:29:39 pts/4       0:00 grep statd
#
Syntax: grep options filenames.  
The options used are discussed below :
iSearches both uppercase and lowercase characters
lLists the name of files with matching lines
nPrecedes each line with the relative line number in the file
vInverts the search to display lines that do not match pattern
cCounts the lines that contain pattern
wSearches for the expression as acomplete word, ignoring those matches that are sub strings of larger words

Lets see few examples: 

Suppose we want to search for all lines that contain the keyword root in /etc/group file and view their line numbers, we use following option :
# grep -n root /etc/group
1:root::0:
2:other::1:root
3:bin::2:root,daemon
4:sys::3:root,bin,adm
5:adm::4:root,daemon
6:uucp::5:root
7:mail::6:root
8:tty::7:root,adm
9:lp::8:root,adm
10:nuucp::9:root
12:daemon::12:root

To search for all the lines that does not contain the keyword root:

# grep -v root /etc/group
staff::10:
sysadmin::14:
smmsp::25:
gdm::50:
webservd::80:
postgres::90:
unknown::96:
nobody::60001:
noaccess::60002:
nogroup::65534:
cta::101:
rancid::102:
mysql::103:
torrus::104:

To search for the names of the files that contains the keyword root in /etc directory :

# cd /etc
# grep -l root group passwd hosts
group
passwd

To count the number of lines containing the pattern root in the /etc/group file:

# grep -c root group
11

Using regular expression Metacharacters with grep command:


MetacharPurposeExampleResult
^Begining of line Anchor'^test'Matches all lines begining with test
$End of line anchor'test$'Matches all the lines ending with test
.Matches one char't..t'Matches all the line starting and ending with t and 2 char between them
*Matches the preceding item 0 or more times'[a-s]*'Matches all lines starting with lowercase a-s
[]Matches one character in the pattern'[Tt]est'Matches lines containing test ot Test
[^]Matches one character not in pattern'[^a-s]est'Matches lines that do not contain "a" though "s" and followed by est


Using egrep command : 
With egrep we can search one or more files for a pattern using extended regular expression metacharacters.

Following table describes the Extended Regular Expression Metacharacters :

Metachar
Purpose
Example
Result
+Matches one of more preceding chars'[a-z]+est'Matches one or more lowercase letters followed by est(for example chest, pest, best, test, crest etc
x|yMatches either x or y'printer|scanner'Matches for either expression
(|)Groups characters'(1|2)+' or 'test(s|ing)'Matches for one or more occurrence. 

Syntax: egrep -options pattern filenames
Examples:
#egrep '[a-z]+day' /ravi/testdays
sunday
monday
friday
goodday
badday
In the above example, we searched for the letter ending with day in the file /ravi/testdays

#egrep '(vacation |sick)' leave' /ravi/leavedata

vacation leave on 7th march
sick leave on 8th march
In the above example we are displaying sick leave and vacation leave from file /ravi/leavedata

Using fgrep command :

It searches for all the character regardless of it being metacharacter as we have seen in case of grep and egrep commands.
Syntax: fgrep options string filenames
Example:
#fgrep '$?*' /ravi/test
this is for testing fgrep command $?*
#

Using Find command :

This command is used to locate files and directories. You can relate it with windows search in terms of functionality.
Syntax: find pathnames expressions actions

Pathname: The absolute or relative path from where the search begins.


Expressions: The search criteria is mentioned here. We will discuss search criteria below in details.



Expression
Definition
-name filenameFinds the file matching.
-size [+|-]nFinds files that are larger than +n, smaller than -n, or exactly n.
-atime [+|-]nFind files that have been accessed more than +n days, less than -n or exactly n days ago.
-mtime [+|-]nFind files that have been modified more than +n days, less than -n or exactly n days ago.
-user loginIDFinds all files that are owned by the loginID name.
-typeFinds a file type : f for file, d for directory.
-permFind files that have certain access permission bits.

Action: Action required after all the files have been found. By default it displays all the matching pathnames 

Action
Definition
-exec command {} \;Runs the specified command on each file located.
-ok commadn {} \:
Requires confirmation before the find command applies the command to each file located.
-printPrints the search result
-lsDisplays the current pathname and associated stats : inode number, size in kb, protection mode, no. of hard links and the user.
-user loginIDFinds all files that are owned by the loginID name.
-typeFinds a file type : f for file, d for directory.
-permFind files that have certain access permission bits.

Examples:

#touch findtest
#cat >> findtest
This is for test.
#find ~ -name findtest -exec cat {} \;
This is for test.
#
The above examples searches for the file : findtest and displays its content. We can also use 'ok' option instead of exec. This will prompt for confirmation before displaying the contents of file findtest.

If we want to find files larger than 10 blocks (1 block = 512bytes) starting from /ravi directory, following command is used :

#find /ravi -size +10

If we want to see all files that have not been modified in the last two days in the directory /ravi, we use :

#find /ravi -mtime +2



Printing Files

lp comand : This command is located in /usr/bin directory. It is used to submit the print request to the printer. 
Syntax:
/usr/bin/lp <file name> 
/usr/bin/lp -d <printer name > <file name>

The options for the lp command are discussed below :

Option
Description
dIt is used to specify the desired printer. It is not required if default printer is used
oIt is used to specify that the banner page should not be printed
nPrint the number of copies specified
mIt send email after the print job is complete

lpstat command : It displays the status of the printer queue.  The Syntax for this command is as follows:
lpstat -option <printer name>

The options for the lpstat command are discussed below :
Option
Description
pDisplays the status of all printers
oDisplays the status of all output printers
dDisplays the default system printer
tDisplays the complete status information of all printers
sDisplay the status summary of all printers
aDisplays which printers are accepting request

The output of the lpstat command is in the following format :
<request ID> <user ID> <File Size> <Date & Time> <status>

Cancel command : It is used to cancel the print request. The Syntax:
cancel <request ID>
cancel -u <user name>
Note: We can use lpstat command to get the request ID.