I need to loop over all directories in $PATH variable. Something like this:

for directory in "$PATH"; do 
    echo $directory

So if my $PATH variable is /usr/bin /bin /usr/sbin /sbin /usr/local/bin I need to have a loop with five directories: /usr/bin, /bin, /usr/sbin, /sbin, /usr/local/bin, /usr/local/go/bin

How can I do it ?

3 Answers

ruakh On Best Solutions

I think the best approach is this:

while IFS= read -r -d : ; do

  printf '%s\n' "$directory"
done <<< "$PATH:"

which uses the read command to read "lines", with : being the line terminator. (Setting IFS to the empty string ensures that read won't try to split the line into words, in case your path contains any whitespace or whatnot.)

David C. Rankin On

Another alternative with bash is simply to create an array where each element holds a component of your $PATH and then you can simply loop over the array as needed, e.g.

dirs=( $(IFS=:; echo $PATH) )
for d in "${dirs[@]}"; do
    ## use d as needed

If you only need to traverse the list once, then ruakh's while loop is fine.

Sergio On

You can use variable substitution to replace every colon in $PATH with newlines:

for p in ${PATH//:/$'\n'}; do
  echo $p

This won't work if there are spaces in the directories of $PATH