Path Manipulation Tricks
Advanced Path Management Techniques
Directory Path Expansion
## Expand home directory
echo ~
## Expand current user's home directory
echo $HOME
Path Manipulation with Bash
Using Basename and Dirname
## Extract filename from path
basename /home/user/documents/report.txt
## Output: report.txt
## Extract directory path
dirname /home/user/documents/report.txt
## Output: /home/user/documents
graph TD
A[Path Manipulation] --> B[Basename]
A --> C[Dirname]
A --> D[Path Expansion]
A --> E[Variable Substitution]
Advanced Path Operations
Technique |
Command |
Example |
Result |
Remove Extension |
basename file.txt .txt |
basename report.pdf .pdf |
report |
Get Full Path |
readlink -f |
readlink -f ./script.sh |
/full/path/script.sh |
Resolve Symlinks |
realpath |
realpath ~/link |
/actual/target/path |
Shell Parameter Expansion
## Path manipulation with parameter expansion
file="/home/user/documents/report.txt"
## Get filename
echo ${file##*/}
## Get directory path
echo ${file%/*}
Recursive Path Handling
## Find all directories
find /home -type d
## Search files in multiple paths
find /etc /home -name "*.conf"
Path Validation Techniques
## Check if directory exists
if [ -d "/path/to/directory" ]; then
echo "Directory exists"
fi
## Check if path is readable
test -r /path/to/file && echo "Readable"
Advanced Scripting Patterns
Dynamic Path Construction
## Construct paths dynamically
base_dir="/home/user"
project_name="myproject"
full_path="${base_dir}/${project_name}"
mkdir -p "$full_path"
Best Practices
- Use parameter expansion for path manipulation
- Validate paths before operations
- Handle paths with spaces carefully
- Use quotes to prevent word splitting
With LabEx, you can explore and practice these advanced path manipulation techniques in a safe, interactive Linux environment.