|
Shell provides several tools for manipulating file paths. The key commands are dirname, basename, and realpath (or readlink).
|
|
|
Output:
Path: /home/user/documents/report.txt Directory: /home/user/documents |
|
|
Multiple |
|
|
Output:
Parent: /home/user |
|
|
|
|
|
Output:
Filename: report.txt |
|
|
|
|
|
Output:
Without .txt: report |
|
|
Combine |
|
|
Output:
Dir: /var/log, Name: syslog |
|
|
Handle paths with spaces: |
|
|
Output:
Path with spaces: Dir: /home/user/my documents Name: my file.txt |
|
|
Parameter expansion alternatives (faster, no subshell): |
|
|
Output:
Parameter expansion: Directory: /path/to Filename: document.tar.gz Extension: gz Without ext: /path/to/document.tar Base name: document.tar.gz Base without ext: document.tar |
|
|
Get absolute path with |
|
|
Output:
Absolute paths: /tmp |
|
|
|
|
|
Output:
Current directory: /tmp |
|
|
Canonical path (resolve symlinks): |
|
|
Output:
Canonical /usr/bin: /usr/bin |
|
|
Check if path is absolute: |
|
|
Output:
/home/user is absolute relative/path is relative |
|
|
Join paths safely: |
|
|
Output:
Joined: /home/user/documents Joined: /home/user/documents |
|
|
Get file extension: |
|
|
Output:
Extension of file.txt: txt Extension of archive.tar.gz: gz Extension of noext: |
|
|
Change extension: |
|
|
Output:
Change ext: file.md |
|
|
Relative path from one location to another via GNU |
|
|
Output:
docs/file.txt |
|
|
Path normalization (remove |
|
|
Output:
Normalized /tmp/.: /tmp |
|
|
Check common path conditions: |
|
|
Output:
Path checks for /tmp: Exists Is directory Not regular file Not symlink Is readable Is writable Is executable |
|
|
Script’s own directory: |
|
|
Output:
Script location: $0: /script |
|
|
Split path into components: |
|
|
Output:
Path components: usr local bin script |
|
|
Find common prefix of paths: |
|
|
Output:
Common prefix: /home/user/ |
|