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

File and Directory Management.

File and Directory Management completed. • ls — List directory contents. • cd — Change directory. • pwd — Print working directory. • mkdir — Create a directory. • rmdir — Remove an empty directory. • rm — Remove files or directories. • cp — Copy files or directories. • mv — Move or rename files or directories. • touch — Create an empty file or update file timestamps. • find — Search for files and directories. • basename — Extract the file name from a path. • dirname — Extract the directory part
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

File and Directory Management.

File and Directory Management completed. • ls — List directory contents. • cd — Change directory. • pwd — Print working directory. • mkdir — Create a directory. • rmdir — Remove an empty directory. • rm — Remove files or directories. • cp — Copy files or directories. • mv — Move or rename files or directories. • touch — Create an empty file or update file timestamps. • find — Search for files and directories. • basename — Extract the file name from a path. • dirname — Extract the directory part
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

File and Directory Management

First understand the prompt on cli.

prompts:

[vagrant@app01 ~]$:
 vagrant: Username of the logged-in user.
 app01: Hostname of the system.
 ~: Current directory (home directory of the user).
 $: Indicates this is a normal user.
 #: Indicates this is a superuser.

Command: man
Definition:
The man command in Linux is used to display the manual (help) pages for other
commands and programs, providing detailed information about their usage,
options, and arguments.
Uses:
1. To view the documentation of commands, functions, and system calls.
2. Helpful for understanding how to use a command, its syntax, and available
options.
3. Great for learning about new commands or troubleshooting issues.
Example:

 To view the manual page for the ls command, you would type:
man ls
This will display detailed information about how to use the ls command, its
options, and examples.
 To exit the manual page, press q (quit).
This command is an essential tool for accessing help and documentation in the
terminal.

Command: --help
Definition:
The --help option provides a quick summary of a command’s syntax, options, and
usage.
Example:

 ls --help
Displays a summary of the ls command and its options.
Use Case:
 To quickly learn the available options for any command without reading the
full manual.

Command: whoami
Definition:
The whoami command displays the username of the currently logged-in user.
Uses:
1. Identifying the current logged-in user.
2. Confirming user identity in shared or multi-user systems.
3. Useful in debugging scripts that depend on user roles.

vagrant pts/0 2024-11-07 12:32 (10.0.2.2)


vagrant: This is the username of the currently logged-in user.
pts/0: This indicates the terminal session being used by the user.
2024-11-07 12:32: This is the date and time when the user logged in.
(10.0.2.2): This shows the IP address from which the user has logged in.

Absolute path of Directory.


 Definition:
An absolute directory is the full path that starts from the root directory (/)
and specifies the exact location of a file or directory in the file system.
 Example:
If there is a file named file.txt in the documents folder located in
/home/vagrant/, the absolute directory would be:
/home/vagrant/documents/file.txt
This path starts from the root / and points directly to the file.

Relative path of Directory.


 Definition:
A relative directory specifies the location of a file or directory in relation to
the current working directory.
 Example:

If you are in the /home/vagrant/ directory, the relative directory to access


file.txt in the documents folder would be:
documents/file.txt

This path is relative to your current location and doesn't need the full path
starting from the root.

Command: pwd
Definition:
The pwd (print working directory) command in Linux shows the absolute path of
the current working directory.
Uses:
1. To display the full path of the directory you're currently in.
2. Useful for confirming your location within the file system when navigating
directories.
3. Helpful in scripts to get the current directory path.
Example:

If you are in the /home/vagrant directory, the output of the pwd command will
show:
/home/vagrant

Command: mkdir
Definition:
The mkdir command in Linux is used to create directories. It is commonly used to
organize files and directories in the filesystem. With options, it can create nested
directories, set permissions, and display messages.
Pattern to Use:
 Basic Syntax:
mkdir [options] directory_name
Options:
1. -p — Create parent directories if they do not exist.
2. -m — Set file permissions for the new directory.
3. -v — Verbose mode to show a message for each created directory.

Example Cases:
1. Create a single directory:
o Command: mkdir project
o Creates a directory named project in the current location.
o

2. Create multiple directories at once:


o Command: mkdir dir1 dir2 dir3
o Creates directories dir1, dir2, and dir3 in the current location.

3. Create a directory in a specific location:


o Command: mkdir /home/vagrant/new_folder
o Creates new_folder inside the /home/vagrant directory.
4. Create parent directories:
o Command: mkdir -p /home/vagrant/level1/level2
o Creates level1 and level2 directories if they do not already exist.

5. Set permissions while creating a directory:


o Command: mkdir -m 750 secure_dir
o Creates secure_dir with permissions set to 750.

6. Display a message after creating directories:


o Command: mkdir -v example_dir
o Outputs:
mkdir: created directory 'example_dir'
7. Combine options to create nested directories with permissions:
o Command: mkdir -p -m 755 /tmp/project/src
o Creates the /tmp/project/src directory structure with 755
permissions.

Command: cd
Pattern to Use:
 Basic Syntax:
cd [directory]
Definition:
The cd (change directory) command is used to navigate between directories in the
file system.
Examples:
1. Changing to a specific directory:
To move to a specific directory, provide its full path or relative path.
o Example: cd /home/vagrant
This changes the current directory to /home/vagrant.
o

2. Changing to the home directory:


To go to the home directory of the current user, use cd ~.
o Example: cd ~
This takes you to the home directory (/home/vagrant for the user
vagrant).
o

3. Changing to the parent directory:


Use cd .. to move one level up (to the parent directory).
o Example: cd ..
This moves you to the parent directory of the current working
directory.
o

4. Changing to the previous directory:


Use cd - to switch to the directory you were in just before.
o Example: cd -
These switches to the previous directory and prints the path of it.
o

5. Changing to a directory using relative path:


You can use a relative path based on your current directory.
o Example: cd documents
If you're in /home/vagrant, this moves you to
/home/vagrant/documents.
Command: ls
Pattern to Use:
 Basic Syntax:
ls [options] [directory]
Definition:
The ls command in Linux is used to list the contents of a directory, such as files
and subdirectories. It is commonly used to explore and view files within a
directory.
Examples:
1. List contents of the current directory:
o Command: ls
o This lists all files and directories in the current directory.
o

2. List contents of a specific directory:


o Command: ls /home/vagrant
o This lists files and directories within /home/vagrant.
o

3. List with detailed information (long format):


o Command: ls -l
o Displays file permissions, owner, size, and modification date.
o

4. Include hidden files:

o Command: ls -a
o Lists all files, including hidden ones (those that start with a dot .).
o

5. List files with human-readable sizes:


o Command: ls -lh
o Displays file sizes in a human-readable format (e.g., KB, MB).
o

6. Recursively list files in subdirectories:


o Command: ls -R
o Lists files in the current directory and all its subdirectories.
o

7. Sort files by size:


o Command: ls -S
o Sorts files by size, from largest to smallest.
o

8. Sort files by modification time:


o Command: ls -t
o Sorts files by their modification time, displaying the most recently
modified first.
o
Command: touch
Pattern to Use:
 Basic Syntax:
touch [options] [file_name]

Definition:
The touch command in Linux is used to create empty files or update the access
and modification times of existing files. If the specified file does not exist, it is
created as an empty file.
Examples:
1. Create a new empty file:
o Command: touch file.txt
o This creates an empty file named file.txt in the current directory.
o

2. Update the timestamp of an existing file:


o Command: touch file.txt
o If file.txt already exists, this updates its access and modification
timestamps to the current time.
o

3. Create multiple files:


o Command: touch file1.txt file2.txt file3.txt
o This creates three empty files: file1.txt, file2.txt, and file3.txt.
o

4. Create a file with a specific timestamp:


o Command: touch -t 202311071200 file5.txt
o This sets the timestamp of file.txt to November 7, 2023, 12:00 PM.
o

Use Cases:
 Creating Empty Files: To quickly create new files without content.
 Updating Timestamps: Used to modify the access and modification
timestamps of files without changing their content.
 Automation: Commonly used in scripts to create files or manage file
timestamps.

Command: cp
Pattern to Use:
 Basic Syntax:
cp [options] source destination
Definition:
The cp command is used to copy files and directories from one location to
another in the file system.
Options:
 -r: Copies directories and their contents recursively.
 -i: Prompts for confirmation before overwriting an existing file.
 -f: Forces overwrite without prompting.
 -u: Copies only if the source is newer or the destination is missing.
 -v: Shows verbose output, listing the files as they are copied.
 -a: Copies files and directories, preserving attributes (permissions,
timestamps).
 -n: Prevents overwriting existing files.
 --backup: Makes a backup before overwriting a file.
Examples:
1. Copy a file Relative Path:
cp file1.txt /root

2. Copy a directory recursive:


cp -r dir1 /root

3. Copy a file Absolute Path


cp /home/vagrant/file3.txt /root/
Note: The advantage of using an absolute path is that you can execute the command from any directory.

Command: mv
Pattern to Use:
 Basic Syntax:
mv [options] source destination
Definition:
The mv command is used to move or rename files and directories in the Linux file
system.
Options:
 -i: Prompts for confirmation before overwriting an existing file.
 -f: Forces the move and overwrites any existing file at the destination
without prompting.
 -u: Moves the file only if the source is newer than the destination file or if
the destination file is missing.
 -v: Provides verbose output, showing the files being moved.
 -n: Prevents overwriting files at the destination.
 -b: Creates a backup of the destination file before overwriting it.
Examples:
1. Move a file (Absolute Path):
mv /home/user/file1.txt /home/user/backup/
This moves file1.txt from /home/user/ to the backup/ directory.

2. Move a file (Relative Path):


mv file1.txt backup/
This moves file1.txt from the current directory to the backup/ subdirectory.

3. Rename a file:sssssssss
mv file1.txt file12.txt
This renames file1.txt to file12.txt in the current directory.

4. Move a directory:
mv dir1 backup/
This moves the entire directory dir1 into the backup/ directory.
5. Move with confirmation to overwrite:
mv -i file1.txt backup/
This prompts for confirmation before overwriting file1.txt in the backup/
directory.

6. Move with verbose output:


mv -v file1.txt /home/user/backup/
This moves file1.txt to the backup/ directory and displays the operation
details.
Use Cases:
 Renaming Files: Change the name of files or directories.
 Moving Files: Relocate files or directories to different locations.
 File Organization: Organize files by moving them into appropriate
directories.
 Backup: Move files to backup directories while retaining the original file
structure.

Command: rmdir
Definition:
The rmdir command in Linux is used to delete empty directories.
Pattern to Use:
rmdir [options] [directory_name(s)]
Options:
1. -p — Remove parent directories if they are empty.
2. --ignore-fail-on-non-empty — Suppress errors for non-empty directories.
3. --verbose — Show a message for each removed directory.
4. --help — Display help information.
5. --version — Display version information.
Examples:
1. Remove a single empty directory:
Command: rmdir test_dir

2. Remove a directory and its empty parent directories:


Command: rmdir -p /home/user/dir1/dir2

3. Suppress errors for non-empty directories:


Command: rmdir --ignore-fail-on-non-empty non_empty_dir
4. Show messages for removed directories:
Command: rmdir --verbose dir3

5. Check version or help information:


Command: rmdir --version or rmdir --help

Command: rm
Pattern to Use:
 Basic Syntax:
rm [options] file(s)
Definition:
The rm command is used to remove files or directories in Linux. Once removed,
the files cannot be recovered unless there is a backup.
Options:
 -r: Recursively removes directories and their contents.
 -f: Forces the removal of files without prompting for confirmation, even if
they are write-protected.
 -i: Prompts for confirmation before removing each file.
 -v: Displays verbose output, showing the files being removed.
 --no-preserve-root: Avoids protecting the root directory (/) from being
deleted (not recommended to use on root directories).
 -d: Removes empty directories.
 --preserve-root: This option is used to prevent the accidental deletion of
the root directory (/), which is the default behavior.
Examples:
1. Remove a single file:
rm file1.txt
This removes file1.txt from the current directory.
2. Remove multiple files:
rm file1.txt file2.txt
This removes both file1.txt and file2.txt in one command.

3. Remove a directory and its contents:


rm -r dir1
This recursively removes the directory dir1 and all its contents, including
subdirectories.
4. Forcefully remove a file without confirmation:
rm -f file1.txt
This removes file1.txt without asking for confirmation, even if it is write-
protected.

5. Prompt before removing each file:


rm -i file1.txt
This prompts you to confirm before deleting file1.txt.

6. Verbose output while removing files:


rm -v file1.txt
This removes file1.txt and displays a message indicating the file is being
removed.
7. Remove an empty directory:
rm -d emptydir
This removes the directory emptydir only if it is empty.

8. Forcefully remove a non-empty directory:


rm -rf dir1
This recursively removes the directory dir1 and all of its contents, including
subdirectories, without asking for confirmation.

Use Cases:
 File Deletion: Use rm to permanently delete files you no longer need.
 Clean Up: Remove unwanted or temporary files in a directory.
 Directory Cleanup: Delete directories and their contents when cleaning up
space.
 Scripting: Automate file deletion in scripts for maintenance or cleanup
tasks.
Caution: The rm command is irreversible; once a file is removed, it cannot be
recovered unless you have a backup or use a data recovery tool. Always double-
check the files you are deleting, especially when using options like -f and -r.
Command: find
Definition:
The find command in Linux is used to search for files and directories in a directory
hierarchy based on various criteria such as name, size, type, and more.
Pattern to Use:
find [path] [options] [expression]
Options (Short and Simple):
1. -name — Search for files by name.
2. -type — Specify the type of file (e.g., f for file, d for directory).
3. -size — Search for files based on size (e.g., +10M for files larger than 10
MB).
4. -user — Search for files owned by a specific user.
5. -group — Search for files belonging to a specific group.
6. -perm — Search for files with specific permissions.
7. -mtime — Search for files modified within a certain number of days.
8. -exec — Execute a command on the matched files.
9. -iname — Case-insensitive search by name.
10.-empty — Search for empty files or directories.
Examples:
1. Find files by name:
Command: find /home -name "file.txt"
Finds a file named file.txt in the /home directory.
2. Find directories by name:
Command: find / -type d -name "docs"
Finds directories named docs from the root directory.

3. Find files by size:


Command: find /var -size +10M
Finds files larger than 10 MB in the /var directory.

4. Find files modified in the last 7 days:


Command: find /tmp -mtime -7
Finds files in /tmp modified within the last 7 days.
5. Find files and execute a command:
Command: find /logs -name "*.log" -exec rm {} \;
Deletes all .log files in /logs.
6. Find files with specific permissions:
Command: find / -perm 644
Finds files with 644 permissions.

7. Case-insensitive search:
Command: find . -iname "README.txt"
Searches for README.txt, ignoring case sensitivity.

8. Find empty directories:


Command: find /home -type d -empty
Finds empty directories in /home.
The find command is powerful and versatile, making it a key tool for locating files
or directories and performing actions on them.

Command: basename
Definition:
The basename command in Linux extracts the file name or the final component of
a path, removing the leading directory components or a specified suffix. It is
commonly used in scripts to isolate file names from full paths.
Pattern to Use:
basename [path] [suffix]
Options (Short and Simple):
1. No options are typically used — the command works directly with a path.
2. [suffix] — An optional suffix to remove from the file name.
Examples:
1. Extract the file name from a full path:
Command: basename /home/user/documents/report.txt
Output: report.txt
2. Remove a specific suffix:
Command: basename /home/user/scripts/run.sh .sh
Output: run
3. With directory paths:
Command: basename /home/user/
Output: user
4. In a script to extract file names:
Command:
filepath="/var/logs/errors.log"
echo "File name: $(basename $filepath)"
Output: errors.log
The basename command is particularly useful in automation, where paths need to
be parsed and only specific components are required.

Command: dirname
Definition:
The dirname command in Linux is used to extract the directory path from a given
file path. It removes the file name portion, leaving only the directory structure. It
is helpful when you need to obtain the directory portion of a path for scripting or
navigation.
Pattern to Use:
dirname [path]
Options (Short and Simple):
1. No options are typically used with dirname — it works directly with the
path.
Examples:
1. Extract the directory path from a full file path:
Command: dirname /home/user/documents/file.txt
Output: /home/user/documents
2. Extract directory path from a file path with a directory:
Command: dirname /home/user/scripts/run.sh
Output: /home/user/scripts
3. Using dirname in a script to work with file paths:
Command:
filepath="/var/logs/system.log"
echo "Directory path: $(dirname $filepath)"
Output: /var/logs
dirname is commonly used in scripts to work with paths and extract the directory
portion for file manipulation or navigating the file system.

You might also like