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

#!/bin/bash
# Description: current path
echo "${PATH//:/$'\n'}"

Output:

/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
/usr/games
/usr/local/games
/snap/bin

How It Works

${PATH//:/$'\n'}
  │    ││ └─────── Replacement: $'\n' (newline)
  │    │└───────── Pattern: : (colon)
  │    └────────── // means "replace ALL occurrences"
  └─────────────── Variable: PATH

Breakdown

  1. PATH - Environment variable containing colon-separated directories
  2. //: - Replace all colons (:) globally
  3. $'\n' - ANSI-C quoting for actual newline character
  4. Result - Each directory appears on its own line

Single vs Double Slash

# Single / - replaces FIRST occurrence only
echo "${PATH/:/$'\n'}"
# Output:
# /usr/local/sbin
# /usr/local/bin:/usr/sbin:/usr/bin...
#                ↑ remaining colons unchanged

# Double // - replaces ALL occurrences
echo "${PATH//:/$'\n'}"
# Output: each directory on separate line ✓

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):

filename="document.txt"
echo "${filename%.txt}"     # document

Remove from beginning (prefix):

filepath="/home/user/file.txt"
echo "${filepath#/*/}"      # user/file.txt
echo "${filepath##*/}"      # file.txt (filename only)

String replacement:

text="hello world"
echo "${text/world/bash}"   # hello bash (first match)
echo "${text//o/0}"         # hell0 w0rld (all matches)

Why Use Parameter Expansion?

Performance: No external process spawned (unlike sed, awk, cut)

# Slow - spawns sed process
filename=$(echo "doc.txt" | sed 's/.txt//')

# Fast - pure shell builtin
filename="doc.txt"
echo "${filename%.txt}"

Portability: Works in any POSIX shell

Simplicity: Clean, readable syntax for common operations

Alternative Methods

Using external tools (slower but sometimes clearer):

# Using tr
echo "$PATH" | tr ':' '\n'

# Using sed
echo "$PATH" | sed 's/:/\n/g'

# Using awk
echo "$PATH" | awk -F: '{for(i=1;i<=NF;i++) print $i}'

ANSI-C Quoting

The $'...' syntax enables escape sequences:

echo $'\n'      # newline
echo $'\t'      # tab
echo $'\r'      # carriage return
echo $'\\'      # backslash
echo $'\x41'    # hex (outputs: A)

Practical Use Cases

Display CSV on separate lines:

csv="name,age,city,country"
echo "${csv//,/$'\n'}"

Replace spaces in filenames:

filename="my document.txt"
safe="${filename// /_}"     # my_document.txt

Remove all vowels:

word="beautiful"
echo "${word//[aeiou]/}"    # btfl

Convert dots to dashes:

version="1.2.3.4"
echo "${version//./-}"      # 1-2-3-4

Path Manipulation Examples

filepath="/home/user/documents/report.txt"

# Directory path
echo "${filepath%/*}"       # /home/user/documents

# Filename only
echo "${filepath##*/}"      # report.txt

# Extension
echo "${filepath##*.}"      # txt

# Basename (no extension)
filename="${filepath##*/}"
echo "${filename%.*}"       # report

# Get last two components
echo "${filepath#/*/}"      # user/documents/report.txt

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.

my DevOps Odyssey

“Σα βγεις στον πηγαιμό για την Ιθάκη, να εύχεσαι να ‘ναι μακρύς ο δρόμος, γεμάτος περιπέτειες, γεμάτος γνώσεις.” - Kavafis’ Ithaka.