[erlang-questions] Executing external commands

Fernando Ipar <>
Mon Feb 12 14:10:38 CET 2007


Thanks a lot to everyone who replied.
I messed up some of my replies by not sending them to the list, I'm 
sorry for the out of list e-mails some of you
got!

The port suggestion by Raimo and Richard are very good.
Richard's code runs perfectly on my linux system, and I can get the 
ExitCode with no problems.
One small question though:
After looking at the list D, I was under the impression it would be a 
list of ASCII codes, but list_to_atom(D) exits
with badarg. How do you get the output from that list?.


Michael's suggestion was great too, and if you're running just on unix 
it's probably easier.
Here's a function, based on his examples, that returns {ExitCode, Output}

check(Command) ->
        Output = os:cmd(Command ++ ";echo $?"),
        {match, Start, Length} = 
regexp:first_match(Output,".*\n[0-9][0-9]*\n"),
        Pos = (Start + Length) - 2,
        { string:substr(Output,Pos,1), Output}.

Here are two sample runs:

ext:check("ls /bin").
{"0",
 "alsacard\nalsaunmute\narch\nawk\nbasename\nbash\ncat\nchgrp\nchmod\nchown\ncp\ncpio\ncsh\ncut\ndate\ndbus-cleanup-sockets\ndbus-daemon\ndbus-send\ndd\ndf\ndmesg\ndnsdomainname\ndoexec\ndomainname\ndumpkeys\necho\ned\negrep\nenv\nex\nfalse\nfgrep\ngawk\ngettext\ngrep\ngtar\ngunzip\ngzip\nhostname\nigawk\nipcalc\nkbd_mode\nkill\nksh\nlink\nln\nloadkeys\nlogin\nls\nmail\nmailx\nmkdir\nmknod\nmktemp\nmore\nmount\nmountpoint\nmv\nnetstat\nnice\nnisdomainname\npgawk\nping\nping6\nps\npwd\nred\nrm\nrmdir\nrpm\nrvi\nrview\nsed\nsetfont\nsetserial\nsh\nsleep\nsort\nstty\nsu\nsync\ntar\ntcsh\ntouch\ntracepath\ntracepath6\ntraceroute\ntraceroute6\ntrue\numount\nuname\nunicode_start\nunicode_stop\nunlink\nusleep\nvi\nview\nypdomainname\nzcat\n0\n"}
4> ext:check("lsss /bin").
{"7","sh: line 1: lsss: command not found\n127\n"}
5>

Thanks again for all the help.
Fernando.





More information about the erlang-questions mailing list