Shell – Could PATH contain newlines

newlinespathshell

It is known that a path could contain newlines in any of its components.

Should we conclude then that the environment variable $PATH could contain newlines ?

If so, how to split the $PATH into its elements, similar to (Bourne like):

    IFS=':' ; set -f
    for var in $PATH
    do
        echo "<$var>"
    done

But if it could be done without changing IFS, even better.

Best Answer

In POSIX shells, $IFS is a field delimiter, not separator, so a $PATH value like /bin:/usr/bin: would be split into /bin and /usr/bin instead of /bin, /usr/bin and the empty string (meaning the current directory). You need:

IFS=:; set -o noglob
for var in $PATH""; do
  printf '<%s>\n' "$var"
done

To avoid modifying global settings, you can use a shell with explicit splitting operators like zsh:

for var in "${(s/:/@)PATH}"; do
  printf '<%s>\n' "$var"
done

Though in that case, zsh already has the $path array tied to $PATH like in csh/tcsh, so:

for var in "$path[@]"; do
  printf '<%s>\n' "$var"
done

In any case, yes, in theory $PATH like any variable could contain newline characters, the newline character is not special in any way when it comes to file path resolution. I don't expect anyone sensible would put a directory with newline (or wildcards) in their $PATH or name a command with newline in its name. It's also hard to imagine a scenario where someone could exploit a script that makes the assumption that $PATH won't contain newline characters.

Related Question