How to display $PATH as one directory per line?

I cannot figure out how to list the various paths in $PATH separately so that they look like this:

/bin
/usr/bin
/usr/local/bin

How can this be done?


Solution 1:

You can do this with any one of the following commands, which substitutes all occurrences of : with new lines \n.

sed:

$ sed 's/:/\n/g' <<< "$PATH"

tr:

$ tr ':' '\n' <<< "$PATH"

python:

$ python -c 'import sys;print(sys.argv[1].replace(":","\n"))' "$PATH"

Solution 2:

Use bash's Parameter Expansion:

echo "${PATH//:/$'\n'}"

This replaces all : in $PATH by a newline (\n) and prints the result. The content of $PATH remains unchanged.
If you only want to replace the first :, remove second slash: echo -e "${PATH/:/\n}"

Solution 3:

Using IFS:

(set -f; IFS=:; printf "%s\n" $PATH)

IFS holds the characters on which bash does splitting, so an IFS with : makes bash split the expansion of $PATH on :. printf loops the arguments over the format string until arguments are exhausted. We need to disable globbing (wildcard expansion) using set -f so that wildcards in PATH directory names don't get expanded.