Path bash script
A simple one-liner to display your PATH variable with each directory on its own line, demonstrating bash parameter expansion for string manipulation.
The Script
Output:
How It Works
Breakdown
PATH- Environment variable containing colon-separated directories//:- Replace all colons (:) globally$'\n'- ANSI-C quoting for actual newline character- Result - Each directory appears on its own line
Single vs Double Slash
Parameter Expansion Basics
The pattern ${variable//pattern/replacement} is called parameter expansion - a built-in bash feature for string manipulation without external commands.
Common Patterns
Remove from end (suffix):
Remove from beginning (prefix):
String replacement:
Why Use Parameter Expansion?
Performance: No external process spawned (unlike sed, awk, cut)
Portability: Works in any POSIX shell
Simplicity: Clean, readable syntax for common operations
Alternative Methods
Using external tools (slower but sometimes clearer):
ANSI-C Quoting
The $'...' syntax enables escape sequences:
Practical Use Cases
Display CSV on separate lines:
Replace spaces in filenames:
Remove all vowels:
Convert dots to dashes:
Path Manipulation Examples
Quick Reference
| Pattern | Description | Example |
|---|---|---|
${var#pattern} |
Remove shortest match from start | ${PATH#/*/} |
${var##pattern} |
Remove longest match from start | ${PATH##*/} |
${var%pattern} |
Remove shortest match from end | ${file%.txt} |
${var%%pattern} |
Remove longest match from end | ${file%%.*} |
${var/pat/rep} |
Replace first match | ${text/old/new} |
${var//pat/rep} |
Replace all matches | ${PATH//:/ } |
Conclusion
Parameter expansion is a powerful bash builtin for fast string manipulation. The PATH display script demonstrates global replacement - a pattern you’ll use frequently in shell scripting.
For simple operations like removing extensions, extracting filenames, or replacing characters, parameter expansion is faster and cleaner than external tools like sed or awk.