Path Operations
Basic Path Manipulation Commands
Copying Files and Directories
## Copy a file
cp source_file destination_path
## Copy a directory recursively
cp -r source_directory destination_path
Moving and Renaming Files
## Move or rename a file
mv source_file destination_path
## Move multiple files
mv file1 file2 file3 destination_directory
Removing Files and Directories
## Remove a file
rm filename
## Remove an empty directory
rmdir directory_name
## Remove a directory and its contents
rm -r directory_name
Advanced Path Operations
Path Expansion and Wildcards
graph TD
A[Path Expansion] --> B[* Matches any characters]
A --> C[? Matches single character]
A --> D[[] Matches character ranges]
Wildcard Examples
## List all .txt files
ls *.txt
## Match files with specific patterns
ls file?.txt
## Match files in character range
ls [a-c]*.txt
Path Manipulation with Bash
Path Environment Variables
Variable |
Description |
Example |
$PATH |
System's executable search path |
/usr/local/bin:/usr/bin |
$HOME |
User's home directory |
/home/username |
$PWD |
Current working directory |
/home/username/documents |
## Get directory name
dirname /path/to/file.txt
## Get filename
basename /path/to/file.txt
## Full path resolution
readlink -f relative_path
File and Directory Permissions
## Change file permissions
chmod 755 filename
## Change ownership
chown user:group filename
Path Traversal Techniques
## Navigate multiple directories
cd ../../another_directory
## Use absolute path for precise navigation
cd /home/username/specific/path
Practical Path Operation Script
#!/bin/bash
## Create a directory structure
mkdir -p /tmp/labex/project/{src,docs,tests}
## Copy files with path preservation
cp -r /source/path/* /destination/path/
## Safe file moving with backup
mv -b original_file backup_location
Best Practices
- Always use absolute paths in scripts
- Be cautious with recursive operations
- Verify paths before critical operations
- Use quotes to handle paths with spaces
By mastering these path operations, you'll become more efficient in managing files and directories in Linux environments like LabEx provides.