realpath
Overview
The realpath
command prints the resolved absolute path by resolving symbolic links and relative path components like .
and ..
.
Syntax
realpath [options] file...
Common Options
Option | Description |
---|---|
-e |
All components must exist |
-m |
No components need exist |
-L |
Resolve symbolic links |
-P |
Don’t resolve symbolic links |
-q |
Suppress error messages |
-s |
Don’t expand symbolic links |
-z |
End output with NUL |
--relative-to=dir |
Print relative path |
--relative-base=dir |
Print absolute unless under base |
Key Use Cases
- Resolve absolute paths
- Canonical path determination
- Symbolic link resolution
- Script portability
- Path normalization
Examples with Explanations
Example 1: Basic Usage
realpath ../file.txt
Returns absolute path of the file
Example 2: Relative Path
realpath --relative-to=/home/user /home/user/docs/file.txt
Returns: docs/file.txt
Example 3: Multiple Files
realpath *.txt
Returns absolute paths for all txt files
Common Usage Patterns
Script location:
SCRIPT_PATH=$(realpath "$0") SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
Canonical comparison:
if [ "$(realpath file1)" = "$(realpath file2)" ]; then echo "Same file" fi
Relative path calculation:
realpath --relative-to="$PWD" /absolute/path
Best Practices
- Use for portable path handling
- Check if files exist when needed
- Handle symbolic links appropriately
- Consider relative vs absolute needs
- Quote paths with spaces
Integration Examples
Config file resolution:
CONFIG=$(realpath "${CONFIG_FILE:-./config.conf}")
Backup path calculation:
BACKUP_PATH=$(realpath "$HOME/../backups")