Suppose echo $PATH
yields /first/dir:/second/dir:/third/dir
.
Question: How does one echo the contents of $PATH
one directory at a time as in:
```
$ newcommand $PATH
/first/dir
/second/dir
/third/dir
```
Preferably, I'm trying to figure out how to do this with a for
loop that issues one instance of echo
per instance of a directory in $PATH
.
If you can guarantee that PATH does not contain embedded spaces, you can:
If there are embedded spaces, this will fail badly.
How about this:
(See sed's
s
command;sed -e 'y/:/\n/'
will also work, and is equivalent to thetr ":" "\n"
from some other answers.)It's preferable not to complicate things unless absolutely necessary: a for loop is not needed here. There are other ways to execute a command for each entry in the list, more in line with the Unix Philosophy:
such as:
This is functionally equivalent to a for-loop iterating over the PATH elements, executing that last
echo
command for each element. The-n 1
tellsxargs
to supply only 1 argument to it's command; without it we would get the same output asecho "$PATH" | sed -e 'y/:/ /'
.Since this uses
xargs
, which has built-in support to split the input, and echoes the input if no command is given, we can write that as:The
-d ':'
tells xargs to use:
to separate it's input rather than a newline, and the-n
tells/bin/echo
to not write a newline, otherwise we end up with a blank trailing line.As an additional option (and in case you need the entries in an array for some other purpose) you can do this with a custom
IFS
andread -a
:Or since the question asks for a version with a for loop:
My idea is to use
echo
andawk
.EDIT
This command is better than my former idea.
You can use
tr
(translate) to replace the colons (:
) with newlines (\n
), and then iterate over that in a for loop.Should do the trick. This will simply take the output of
echo "$PATH"
and replaces any colon with a newline delimiter.Note that the quotation marks around
$PATH
prevents the collapsing of multiple successive spaces in the output of$PATH
while still outputting the content of the variable.