# Export The $PATH Variable, Line-By-Line Inspired by this question on AskUbuntu. Your job is extremely simple. Take the PATH environment variable (echo$PATH) and export it such that each entry (separated by the : character) is on its own line.

For example, if the PATH is /bin:/usr/bin:/usr/local/bin, your program should output:

/bin
/usr/bin
/usr/local/bin


Your program may not return a leading newline, but it may return a single trailing newline. You do not need to check if the PATH is right, or that the directory exists. Your program should take no input, meaning that your program is responsible for getting the PATH itself. You may safely assume that objects in the PATH do not contain : or newlines. However, spaces are fair game.

Reference implementations are present in the answers to the question above.

### Rules

• This is (obviously) code-golf, so the shortest answer will win the prized green checkmark.
• The accepted answer will be tested to make sure it's actually legit.
• Both Windows and *nix entries are accepted.
• However, if you don't explicitly specify Windows, I will try running it in Linux and fail. (If it's obvious (hi, Batch!), you don't need to specify explicitly.)
• Only have one solution per answer. If you have both a Windows and *nix version, I will count the shorter one.
• If two answers have the same length, I will give priority to the one with the higher vote total. If they have the same vote total, I will count the older one. If the time posted is the same, I will choose the one that executes faster. If they execute in the same amount of time, I don't know.

var QUESTION_ID=96334,OVERRIDE_USER=15422;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

• Ahh! It was hard to visit the AskUbuntu Question without giving some golfing tipps. – Roman Gräf Oct 16 '16 at 5:41
• Some of the (shell) answers seem to assume that the path doesn't contain spaces. Should they be corrected? – Dennis Oct 16 '16 at 6:08
• @Dennis Typically, the path variable shouldn't have spaces, but as they can, they should be corrected. However, we can safely assume that paths themselves won't contain : or a newline. – Kaz Wolfe Oct 16 '16 at 7:51
• Is a function acceptable? – corvus_192 Oct 16 '16 at 9:24
• @corvus_192 Unless the challenge explicitly says otherwise, functions are allowed. – Dennis Oct 17 '16 at 15:08

# Z shell (zsh), 13 bytes

<<<${(F)path}  Uses the $path parameter, which is a special array parameter used by the shell that is tied to the $PATH parameter, and a parameter expansion flag to join an array with newlines. • Apparently one does simply out-golf @Dennis... Huh. – wizzwizz4 Oct 17 '16 at 17:45 • How to alias some word to this? I tried alias path="<<<${(F)path}" but when executed it prints /usr/local/bin zsh: no such file or directory: /Library/Apple/usr/bin zsh: no such file or directory: /Library/Apple/bin then goes to sbin – Daniel Springer Jul 18 at 21:14
• @DanielSpringer $path is being expanded during alias definition, which you don't want. Use single quotes instead: alias path='<<<${(F)path}' – GammaFunction Aug 13 at 4:49
• @GammaFunction that worked! Why did double quotes not work? – Daniel Springer Aug 13 at 10:57
• @DanielSpringe Not a lot of space here to explain, here's a pastebin: ix.io/1RyW – GammaFunction Aug 13 at 20:26

## Bash/Coreutils, 17 16 bytes

tr : '
'<<<$PATH  • tr : '\n'<<<$PATH should work as well – Arnauld Oct 15 '16 at 18:54
• It does . . . editing right now – Sergiy Kolodyazhnyy Oct 15 '16 at 18:57
• I think you can remove the spaces around <<< as well (tested on Ubuntu only) – Arnauld Oct 15 '16 at 18:59
• @Arnauld i don't think that's Ubuntu only thing, it's bash thing, so should work accross the distros – Sergiy Kolodyazhnyy Oct 15 '16 at 19:00
• It doesn't save any bytes, but using \\n instead of the quoted variable is more readable imho. – Dennis Oct 16 '16 at 0:23

## Batch, 41 bytes

@for %%a in ("%PATH:;=";"%")do @echo %%~a


PATH is semicolon-delimited on Windows of course. Conveniently, for splits on semicolons by default, but inconveniently, also on spaces, so I have to use string replace trickery to quote each path element before splitting. It then remains to remove the quotes afterwards.

• Running from the command line you can replace %% with % saving 2 bytes. – DavidPostill Oct 16 '16 at 20:08
• @DavidPostill Wouldn't that make it a code snippet rather than a program? – Neil Oct 16 '16 at 20:57
• I'm not sure what the exact code golf rules are, but aren't most of other answers just snippets as well? Most of them require a "shell" of some description to run ... – DavidPostill Oct 16 '16 at 21:08

# Z shell (zsh), 15 bytes

<<<${PATH//:/ }  You can test the code on Anarchy Golf: click use form, select zsh, paste the code and submit. ## Bash (pure), 19 bytes echo "${PATH//:/
}"


Same idea, but with Bash's less golfy syntax. Test it on Ideone.

# Powershell, 20 bytes

$env:PATH-split':'  Edit: • -2 bytes off. Thanks to @TimmyD Old: $env:PATH.split(":")


# Ruby, 25 bytes

puts ENV["PATH"].split":"

• Nice, tiny bit shorter than my answer on the original question on AskUbuntu – Sergiy Kolodyazhnyy Oct 15 '16 at 19:36
• You don't need to count the Ruby invocation, only the program itself, so this is only 26 bytes. – Jordan Oct 16 '16 at 3:01
• @Jordan didn't know that. Is it in FAQ? – Anwar Oct 16 '16 at 5:08
• @Jordan It's shown in the tour itself. So, edited. Thank you for telling that – Anwar Oct 16 '16 at 5:15
• Oh, also you can change split ":" to split":" or split ?: for 1 byte. – Jordan Oct 16 '16 at 5:20

## Perl, 22 bytes

say$ENV{PATH}=~y/:/ /r  Needs -E or -M5.010 to run : perl -E 'say$ENV{PATH}=~y/:/
/r'


### Bash+Python, 43 bytes

Let's use shell's variable expansion. It eliminates calling os.environ , thus less code and less imports. That gives us 46 bytes, and with xnor's trick and removing space before -c we've got 43 bytes.

python -c"print('$PATH'.replace(*':\n'))"  • Note that this fails if a directory with a single quote or a backslash appears in your PATH. – Joey Marianer Oct 16 '16 at 19:54 • @JoeyMarianer Since there can be almost any character in filename/path string, then yes - this may fail and becase PATH will expand to '/dir'1:/dir2' , which gives incorrectly formatted command to python. The backslash doesn't necessarily fail - it just interprets what's in the string itself. IMHO , backslash escapes shouldn't appear in normal user's path names , so for 99% of cases this is OK. I however agree - this should be kept in mind anytime you deal with shell directly or indirectly as in this case – Sergiy Kolodyazhnyy Oct 16 '16 at 20:22 ## Java, 58 bytes System.out.print(System.getenv("Path").replace(';','\n'));  Full program: 106 bytes class E { public static void main (String[] args) { System.out.print(System.getenv("Path").replace(';', '\n')); } }  ## GNU sed + bash, 25 bytes: sed 's/:/\n/g' <<<"$PATH"


If the PATH contains no directory name with whitespace, no quoting needed, 23 bytes:

sed 's/:/\n/g' <<<$PATH  Even shorter, transliterating : to newline, thanks to @Dennis: sed y/:/\\n/<<<"$PATH"


# Vim, 19 bytes

"=$PATH<CR>p:s/:/\r/g<CR> Grab $PATH from the expression register and paste it. Turn the :s into newlines. Nothing tricky.

• They should put this in Vim tutorials. As someone reading about how to get into Vim I appreciate this example. – loa_in_ Oct 16 '16 at 23:04

## PHP, 363533 32 bytes

Saved 1 byte, thanks to Blackhole
Saved 2 bytes, thanks to user59178
saved 1 byte, thanks to Martijn

### *nix version

<?=strtr(getenv(PATH),":","
")?>


### Windows version

<?=strtr(getenv(PATH),";","
")?>

• @RomanGräf *nix is just a way of referring to a Unix-like system. – Arnauld Oct 16 '16 at 11:16
• If you want a "multi-plataform" version, you can use the constant PATH_SEPARATOR – Ismael Miguel Oct 16 '16 at 11:52
• Don't use \n, but a true newline instead, it'll save you one byte. – Blackhole Oct 16 '16 at 18:58
• you can also drop the "s around PATH. You get an "use of undefined constant" notice but it still works, saving you 2 bytes. – user59178 Oct 17 '16 at 13:03
• Using the short echo <?=strtr(getenv(PATH),":","")?> safes a byte (*cant newline in comments) – Martijn Oct 17 '16 at 14:00

# Python 2, 49 bytes

Saving 2 bytes thanks to @xnor and 1 byte by replacing environ with getenv thanks to @Serg and @Oliver

import os
print os.getenv('PATH').replace(*':\n')


For Python 3, just add ( and ) around the print argument and add 1 to the byte count.

• How will this get the input? – Anwar Oct 15 '16 at 19:41
• @Anwar from os.environ['PATH'] , that will return the string – Sergiy Kolodyazhnyy Oct 15 '16 at 19:42
• @Serg ah. got it. – Anwar Oct 15 '16 at 19:46
• replace can take packed arguments replace(*':\n'). – xnor Oct 15 '16 at 20:32
• @KarlNapf Yea, thats the point. This program as-is does not run in Python 3, so you should specify the version it works with. – Denker Oct 15 '16 at 23:34

# C, 85 84 bytes

-1 byte for using #import

#import<stdlib.h>
main(){char*a=getenv("PATH");while(*a)putchar(*a++==58?10:a[-1]);}


## Racket 39 bytes

Using sed command of @heemayl :

(system "sed 's/:/\\n/g' <<<\"$PATH\"")  Ungolfed: (define (f) (system "sed 's/:/\\n/g' <<<\"$PATH\"")
)


Testing:
(f)

Output:

/usr/local/bin
/usr/bin
/bin
/usr/games
/usr/lib/java/bin
/usr/lib/java/jre/bin
#t


# Scala, 31 bytes

sys env "PATH"replace(':','\n')


In scala, a b c is syntactic sugar for a.b(c), so this compiles to sys.env("PATH").replace(':','\n')

# Perl 6,  28 25  24 bytes

%*ENV<PATH>.split(':')».put

put %*ENV<PATH>~~tr/:/\n/

put %*ENV<PATH>~~tr/:/
/


# C#, 64 bytes

x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");


Anonymous function which returns the path variable, each directory on a separate line. Note that x is just a dummy object to save 1 byte instead of using ().

Full program:

using System;

namespace ExportPathVariable
{
class Program
{
static void Main(string[] args)
{
Func<object,string>f= x=>Environment.GetEnvironmentVariable("PATH").Replace(";","\n");

Console.WriteLine(f(0));
}
}
}


Also works on UNIX systems if you replace ; with :, presuming Mono libraries are available. Try it online on ideone, .NET Fiddle returns a security exception.

Alternatively, a full C# program, which is rather verbose:

# C#, 118 bytes

using System;class P{static void Main(){Console.Write(Environment.GetEnvironmentVariable("PATH").Replace(";","\n"));}}


import System.Environment
m ':'='\n'
m x=x

bash-4.3$jq -nr 'env.PATH/":"|.[]' /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /sbin /bin  # Awk, 51 44 characters BEGIN{$0=ENVIRON["PATH"];gsub(":",RS);print}


Thanks to:

• ninjalj for suggesting to use gsub() instead of manipulating built-in variables (-7 characters)

The typical awk way would be to set up the built-in variables which influences how awk manipulates the data automatically:

BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}  Sample run: bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3$awk 'BEGIN{FS=":";OFS=RS;$0=ENVIRON["PATH"];$1=$1;print}'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin

• Doh. You are right, @ninjalj. I was to focused on doing it in awk-specific way. Thank you. – manatwork Oct 19 '16 at 7:41

# Node.js, 36 bytes

_=>process.env.PATH.split:.join



Pretty straight forward.

# MATLAB, 34 bytes

disp(strrep(getenv('PATH'),58,10))


Here is an online demo in Octave with a slight modification since strrep in octave requires the second and third inputs to be char variables rather than numeric values.

# R, 38 bytes

cat(gsub(":","\n",Sys.getenv('PATH')))


Grab the $PATH, replace : with newlines and prints to stdout. You can try it online here. # Groovy, 43 Bytes System.env['PATH'].replaceAll(":","\n")​​​​  # Gema, 36 characters \A=@subst{\\:=\\n;@getenv{PATH}}@end  Sample run: bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3\$ gema '\A=@subst{\\:=\\n;@getenv{PATH}}@end'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin


# Befunge-98 + EVAR fingerprint, 34 bytes

"RAVE"4("HTAP"Gv
:!k@:':-!'0*-, >


Loads the EVAR fingerprint ("RAVE"4() to easily access environment variables, gets the PATH envvar ("HTAP"G), and for each character, exits the program if the character is "\0" (:!k@), substracts ASCII 48 "0" if the char is ASCII 58 ":" (:':-!'0*-), and outputs the character (,).

# ELF/x86, 78 bytes

00000000  7f 45 4c 46 01 00 00 00  43 0f 00 00 43 5f eb 10  |.ELF....C...C_..|
00000010  02 00 03 00 0c 50 eb 10  0c 50 eb 10 04 00 00 00  |.....P...P......|
00000020  5f 5f b1 05 be 49 50 eb  10 3d 20 00 01 00 5f f3  |__...IP..= ..._.|
00000030  a6 75 ef 89 f9 80 3f 3a  75 03 80 2f 30 42 ae 75  |.u....?:u../0B.u|
00000040  f4 4a 04 04 cd 80 93 cd  80 50 41 54 48 3d        |.J.......PATH=|
0000004e


NASM source:

BITS 32                                         ;
ORG 0x10eb5000                                  ;
DB 0x7f,'E','L','F'                             ; | magic       |    +--------------------+
; |             |    |                    |
; PROGRAM HEADERS                               ; |             |    |                    |
DD 1                                            ; |*class   32b | -- | type: PT_LOAD      |
; |*data   none |    |                    |
; |*version   0 |    |                    |
; |*ABI    SysV |    |                    |
DD 0xf43        ; offset = vaddr & (PAGE_SIZE-1); |*ABI vers    | -- | offset             |
; |             |    |                    |
entry:  inc     ebx     ; STDOUT_FILENO         ; |*PADx7       | -- | vaddr = 0x10eb5f43 |
pop     edi     ; discard argc          ; |             |    |                    |
jmp     short skip                      ; |             |    |                    |
DW 2                                            ; | ET_EXEC     | -- |*paddr LO           |
DW 3                                            ; | EM_386      | -- |*paddr HI           |
DD 0x10eb500c                                   ; |*version     | -- | filesz             |
DD 0x10eb500c                                   ; | entry point | -- | memsz              |
DD 4                                            ; | ph offset   | -- | flags: RX          |
; |             |    |                    |
skip:   pop     edi     ; discard argv[0]       ; |*sh offset   | -- |*align              |
pop     edi     ; discard argv[1]=NULL  ; |             |    |                    |
env:    mov     cl,5    ; \ strlen("PATH=")     ; |             |    |                    |
mov     esi,PATH; > "PATH="             ; |*flags    /--|    |                    |
DB 0x3d         ; cmp eax,0x10020               ; |*ehsize      |    +--------------------+
DW 32                                           ; | phentsize   |
DW 1                                            ; | phnum       |
; |             |
pop     edi     ; > envp                ; |*shentsize   |
repe    cmpsb   ; > strcmp(envp,"PATH="); |*shnum       |
jne     env     ; /                     ; |*shstrndx    |
mov     ecx,edi                         ; +-------------+

nlcolon:cmp     byte[edi],58  ; \ if (char == ':')
jne     nosub         ; >
sub     byte[edi],48  ; >   char -= '0'
nosub:  inc     edx           ; > wlen++
scasb                 ; >
jne     nlcolon       ; / while(char != 0)

dec     edx           ; wlen--