简体   繁体   中英

Looping over directories in $PATH variable

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

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

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 ?

I think the best approach is this:

while IFS= read -r -d : ; do
  directory="$REPLY"

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

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, eg

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM