0

I'd like to extract all bin directories from PATH and set it to a variable. I get confused because all the directories appear in a row separated by : but I just want the bin ones.

/home/jo52900/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/X11R6/bin:/usr/games:/opt/bin:/usr/lib/mit/bin:/usr/lib/mit/sbin:/local/bin:/opt/universal/ucmdmgr/bin

How can I do it?

4 Answers4

3

I don't know why you would want to treat the bin directories specially, I am guessing that you just want to see each directory on its own line. If so, you can just do:

printf '%s\n' "$PATH" | tr : '\n'

On my system, for example, where I have many directories in my $PATH whose name doesn't contain bin, that gives:

$ printf '%s\n' "$PATH" | tr : '\n' 
/home/terdon/perl5/bin
/home/terdon/Setups/cd-hit-v4.5.4-2011-03-07
/sbin
/usr/local/sbin
/usr/bin
/usr/sbin
/home/terdon/Setups/PfamScan
/home/terdon/research/data/python
/home/terdon/scripts
/home/terdon/bin

If you really only want to see the bin directories, you can extract them:

$ printf '%s\n' "$PATH" | tr : '\n' | grep '/bin$'
/home/terdon/saphetor/bin
/home/terdon/perl5/bin
/usr/bin
/home/terdon/bin

Or, if you want to do what you show in your answer and also include any directory that hjas the string bin anywhere in its name, and not only those that are actually named bin, you can do:

$ printf '%s\n' "$PATH" | tr : '\n' | grep 'bin'
/home/terdon/saphetor/bin
/home/terdon/perl5/bin
/sbin
/usr/local/sbin
/usr/bin
/usr/sbin
/home/terdon/bin
terdon
  • 242,166
3

Another approach is to ask the shell to split $PATH:

( IFS=: ; printf "%s\n" $PATH )

You can post-process this with grep as necessary.

Stephen Kitt
  • 434,908
1

Assuming you're using zsh:

print -lr $path

The path variable is an array which is automatically synchronized with the colon-separated string in PATH. print -lr prints one element per line without doing backslash interpretation¹.

In case you need this for some other colon-separated list that doesn't have a tied array, you can do the splitting explicitly through a parameter expansion flag.

print -lr ${(s[:])LD_LIBRARY_PATH}

I don't know what you mean by “bin directories”. You can filter using grep, e.g.

print -lr $path | grep bin

Or using parameter expansion features, e.g.

print -lr ${(M)path:#*bin*}

¹ For the nitpickers: this assumes that the list is not empty and the first element does not start with -. Which is a safe bet for $path.

0

I found the solution

echo "$PATH" | grep -o "[^:]*bin[^:]*"
  • 2
    Note that this will only work on systems where grep has an -o option. GNU and BSD grep have this, so it will work on Linux and Mac, but I don't know about other Unices. – terdon Dec 09 '21 at 14:47