[erlang-questions] : Executing external commands

Raimo Niskanen <>
Mon Feb 12 09:57:24 CET 2007


You can also write an improved os:cmd/1 by using
erlang:open_port({spawn,"command"},
                 [{line,80},exit_status,eof,stderr_to_stdout])
and then loop receive all messages from the port to collect
the output and exit status. It is less than one page of code.
I have done it a few times but right now I am in a hurry...



On Sun, Feb 11, 2007 at 07:58:36PM -0800, Michael McDaniel wrote:
>  following works on Linux ...
> 
> $ uname -a
> Linux delora 2.6.17-10-386 #2 Fri Oct 13 18:41:40 UTC 2006 i686 GNU/Linux
> 
> $ erl
> Erlang (BEAM) emulator version 5.5.3 [async-threads:0] [hipe] [kernel-poll:false]
> 
> Eshell V5.5.3  (abort with ^G)
> 1> os:cmd("/bin/ls fubar; echo $?").
> "/bin/ls: fubar: No such file or directory\n2\n"
> 2> os:cmd("/bin/ls foo; echo $?").
> "foo\n0\n"
> 3> init:stop().
> 4> $
> $
> 
>  You can then parse out the return value from the echo.  There are 
>  probably other ways to get the result you are looking for.
> 
>  I think this discussion came up a few months ago.  The above is the result
>  of the particular shell called.
> 
> ~Michael
> 
> 
> On Sun, Feb 11, 2007 at 09:48:10PM -0200, Fernando Ipar wrote:
> > Hi all.
> > 
> > I'm looking for a way to run external commands in erlang and get it's 
> > exit code back to erlang.
> > As far as I understand, os:cmd(Command) only returns the output of 
> > running the program.
> > 
> > Is there a way to get the exit code from the command, or do I have to 
> > implement an external program to run these commands and communicate
> > back and forth with erlang through a port?
> > 
> > What I'm looking for is something like:
> > 
> > os:cmdwithexit(Command,ExitCode),
> > case ExitCode of
> >     0 ->
> >     handleExitOk(Command);
> >     _ ->
> >     handleExitError(Command,ExitCode)
> > end.
> > 
> > 
> > Thanks and regards,
> > 
> > Fernando.
> > _______________________________________________
> > erlang-questions mailing list
> > 
> > http://www.erlang.org/mailman/listinfo/erlang-questions
> > 
> > !DSPAM:52,45cfab6b18342038938978!
> > 
> > 
> 
> -- 
> Michael McDaniel
> Portland, Oregon, USA
> http://autosys.us
> +1 503 283 5284
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions

-- 

/ Raimo Niskanen, Erlang/OTP, Ericsson AB



More information about the erlang-questions mailing list