0

With echo $PATH I get this:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

And what I would like is to get these in the following format:

/usr/local/sbin
/usr/local/bin
...

What I tried to do:

i=1;
for dir in `echo $PATH|cut -d ':' -f $i`
do
    echo $dir
    i=`expr $i + 1`
done

But it doesn't work. Could someone help me with an answer?

Biffen
  • 6,249
  • 6
  • 28
  • 36
Reggie Kapros
  • 101
  • 1
  • 8
  • Frequently asked, e.g., [this](http://stackoverflow.com/questions/25447010/bash-get-all-paths-from-path/25448507) and [this](http://stackoverflow.com/questions/273909/how-do-i-manipulate-path-elements-in-shell-scripts/373476). – Thomas Dickey May 14 '16 at 11:53
  • Then why has no one marked it a duplicate as such? – isakbob Nov 19 '18 at 18:32

3 Answers3

6

tr to the rescue:

echo "$PATH" | tr : '\n'
Biffen
  • 6,249
  • 6
  • 28
  • 36
1

Something like this:

old_IFS=$IFS
IFS=:
set -- $PATH
while [ $# -gt 0 ]; do
    echo $1;
    shift;
done
IFS=$old_IFS
user3159253
  • 16,836
  • 3
  • 30
  • 56
  • Did you mean `$old_IFS` in the last line? Also this approach should have failed had the user performed some other action instead of just echoing `$1`, – sjsam May 14 '16 at 12:07
0

You should do this :

i=0
echo "$PATH" | awk 'BEGIN{RS=":"}{printf "%s\0",$0}'| while read -rd '' line
do
echo "$line"; # or do something else with it?
i=`expr $i + 1`
done

This will take care of non-standard folders in the path variable like
/usr/local folder &/usr/new/continued/in/next/line folder and so on.

You could also use tr instead of awk but replace \n with \0 like below :

echo "$PATH" | tr : '\0' | while ...
sjsam
  • 21,411
  • 5
  • 55
  • 102
  • @Biffen Not `bashism` coz this [wiki article](https://en.wikipedia.org/wiki/Here_document) says it is supported at least in bash, ksh, or zs. Good point anyway. I will edit the answer. – sjsam May 14 '16 at 11:41
  • @Biffen : Appreciate the time, Edited :D – sjsam May 14 '16 at 11:55