Looping through the elements of a path variable in Bash

You can use Bash's pattern substitution parameter expansion to populate your loop variable. For example:

MANPATH=/usr/lib:/usr/sfw/lib:/usr/info

# Replace colons with spaces to create list.
for path in ${MANPATH//:/ }; do
    echo "$path"
done

Note: Don't enclose the substitution expansion in quotes. You want the expanded values from MANPATH to be interpreted by the for-loop as separate words, rather than as a single string.


You can set the Internal Field Separator:

( IFS=:
  for p in $MANPATH; do
      echo "$p"
  done
)

I used a subshell so the change in IFS is not reflected in my current shell.


The canonical way to do this, in Bash, is to use the read builtin appropriately:

IFS=: read -r -d '' -a path_array < <(printf '%s:\0' "$MANPATH")

This is the only robust solution: will do exactly what you want: split the string on the delimiter : and be safe with respect to spaces, newlines, and glob characters like *, [ ], etc. (unlike the other answers: they are all broken).

After this command, you'll have an array path_array, and you can loop on it:

for p in "${path_array[@]}"; do
    printf '%s\n' "$p"
done

Tags:

Linux

Bash