Iterate over $PATH variable using shell script
You can use read
with delimiter set as :
while read -d ':' p; do
echo "$p"
done <<< "$PATH:"
Simplest way is probably to change IFS
to a colon and let the word splitting do it:
IFS=:
for p in $PATH ; do
echo "$p"
done
But that might trigger file name globbing, in the weird case that your PATH
contained characters like *?[]
. You'd need to use set -f
to avoid that.
Though changing IFS
might be considered problematic anyway, since it affects the rest of the script. So in Bash, we could just split the paths to an array with read -a
, this doesn't have a problem with glob characters either:
IFS=: read -a paths <<< "$PATH"
for p in "${paths[@]}" ; do
echo "$p"
done
with echo:
echo "${PATH//:/$'\n'}"
sed:
sed 's/:/\n/g' <<< "$PATH"
tr:
tr ':' '\n' <<< "$PATH"
python:
python -c "import os; print os.environ['PATH'].replace(':', '\n')"
for iterate use for:
for i in ${PATH//:/ }; do echo $i; done