22
\$\begingroup\$

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.

Leaderboard

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>

\$\endgroup\$
  • \$\begingroup\$ Ahh! It was hard to visit the AskUbuntu Question without giving some golfing tipps. \$\endgroup\$ – Roman Gräf Oct 16 '16 at 5:41
  • \$\begingroup\$ Some of the (shell) answers seem to assume that the path doesn't contain spaces. Should they be corrected? \$\endgroup\$ – Dennis Oct 16 '16 at 6:08
  • \$\begingroup\$ @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. \$\endgroup\$ – Kaz Wolfe Oct 16 '16 at 7:51
  • \$\begingroup\$ Is a function acceptable? \$\endgroup\$ – corvus_192 Oct 16 '16 at 9:24
  • \$\begingroup\$ @corvus_192 Unless the challenge explicitly says otherwise, functions are allowed. \$\endgroup\$ – Dennis Oct 17 '16 at 15:08

33 Answers 33

12
\$\begingroup\$

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ Apparently one does simply out-golf @Dennis... Huh. \$\endgroup\$ – wizzwizz4 Oct 17 '16 at 17:45
  • \$\begingroup\$ 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 \$\endgroup\$ – Daniel Springer Jul 18 at 21:14
  • \$\begingroup\$ @DanielSpringer $path is being expanded during alias definition, which you don't want. Use single quotes instead: alias path='<<<${(F)path}' \$\endgroup\$ – GammaFunction Aug 13 at 4:49
  • \$\begingroup\$ @GammaFunction that worked! Why did double quotes not work? \$\endgroup\$ – Daniel Springer Aug 13 at 10:57
  • \$\begingroup\$ @DanielSpringe Not a lot of space here to explain, here's a pastebin: ix.io/1RyW \$\endgroup\$ – GammaFunction Aug 13 at 20:26
13
\$\begingroup\$

Bash/Coreutils, 17 16 bytes

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

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Running from the command line you can replace %% with % saving 2 bytes. \$\endgroup\$ – DavidPostill Oct 16 '16 at 20:08
  • \$\begingroup\$ @DavidPostill Wouldn't that make it a code snippet rather than a program? \$\endgroup\$ – Neil Oct 16 '16 at 20:57
  • \$\begingroup\$ 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 ... \$\endgroup\$ – DavidPostill Oct 16 '16 at 21:08
9
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

Powershell, 20 bytes

$env:PATH-split':'

Edit:

  • -2 bytes off. Thanks to @TimmyD

Old:

$env:PATH.split(":")
\$\endgroup\$
5
\$\begingroup\$

Ruby, 25 bytes

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

Perl, 22 bytes

say$ENV{PATH}=~y/:/
/r

Needs -E or -M5.010 to run :

perl -E 'say$ENV{PATH}=~y/:/
/r'
\$\endgroup\$
3
\$\begingroup\$

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'))"
\$\endgroup\$
  • \$\begingroup\$ Note that this fails if a directory with a single quote or a backslash appears in your PATH. \$\endgroup\$ – Joey Marianer Oct 16 '16 at 19:54
  • \$\begingroup\$ @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 \$\endgroup\$ – Sergiy Kolodyazhnyy Oct 16 '16 at 20:22
3
\$\begingroup\$

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'));
    }
}
\$\endgroup\$
3
\$\begingroup\$

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"
\$\endgroup\$
3
\$\begingroup\$

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.

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

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

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.

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

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]);}
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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')

\$\endgroup\$
1
\$\begingroup\$

Perl 6,  28 25  24 bytes

%*ENV<PATH>.split(':')».put
put %*ENV<PATH>~~tr/:/\n/
put %*ENV<PATH>~~tr/:/
/
\$\endgroup\$
1
\$\begingroup\$

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"));}}
\$\endgroup\$
1
\$\begingroup\$

Haskell, 72 bytes

import System.Environment
m ':'='\n'
m x=x 
map m<$>getEnv"PATH">>=putStr

An expensive import and no replace within the standard library make it quite long.

\$\endgroup\$
  • \$\begingroup\$ surely m ':'... doesn't need that space? \$\endgroup\$ – cat Oct 18 '16 at 10:30
  • 1
    \$\begingroup\$ @cat: the space is mandatory, because ' is a valid character within identifiers. Without space we'd define a function named m'. \$\endgroup\$ – nimi Oct 18 '16 at 13:56
1
\$\begingroup\$

C (x86), 60 bytes

f(){char*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}

This won't work on 64-bit platforms without including stdlib.h, since getenv returns an int (32 bits) while char pointers are 64 bits wide.

I have yet to find an online 32-bit C compiler.

C (x86-64), 70 bytes

f(){char*getenv(),*p=getenv("PATH");for(;*p;p++)putchar(*p-58?*p:10);}

Instead of including stdlib.h, we declare getenv ourselves as a function returning a char pointer.

I've tested this with gcc and clang on Linux; other setups may cry blood. Try it on Ideone.

\$\endgroup\$
1
\$\begingroup\$

Factor, 28 bytes

for unix-likes. I dunno how to do it on Windows since I'm not at a Windows box.

"PATH"getenv ":" "\n"replace
\$\endgroup\$
1
\$\begingroup\$

jq, 18 characters

(16 characters code + 2 characters command line option)

env.PATH/":"|.[]

Sample run:

bash-4.3$ PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'

bash-4.3$ jq -nr 'env.PATH/":"|.[]'
/usr/local/sbin
/usr/local/bin
/usr/sbin
/usr/bin
/sbin
/bin
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Doh. You are right, @ninjalj. I was to focused on doing it in awk-specific way. Thank you. \$\endgroup\$ – manatwork Oct 19 '16 at 7:41
0
\$\begingroup\$

Node.js, 36 bytes

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

Pretty straight forward.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Groovy, 43 Bytes

System.env['PATH'].replaceAll(":","\n")​​​​
\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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 (,).

\$\endgroup\$
0
\$\begingroup\$

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                                  ;
                                                ;   ELF HEADER    --   PROGRAM HEADER
; ELF HEADER                                    ; +-------------+
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--
        add     al,4
        int     0x80          ; write(1, ecx, wlen)
        xchg    eax,ebx
        int     0x80          ; exit(...)

PATH: db "PATH="
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.