Best Way to execute system commands in go

7,659 views
Skip to first unread message

Rahul R

unread,
Dec 7, 2013, 12:48:35 AM12/7/13
to golang-nuts
Is there an effiecient way to execute system commands in golang. 
Currently , the Command() needs every word to be sent as a parameter.

out, err := exec.Command("g++","test.cpp","-o","test.o").Output()   [1]


is there a way where I can send it as a whole string ? like

out, err := exec.Command("g++ test.cpp -o test.o").Output()     [2]


Option 1 seems difficult since you dont know the commands you will be executing at run-time.  Is there a way to implement option [2] or rather a smarter way to convert option[2] to option 1 ? 

Just out of curiosity why doesnt Golang implicity support [2] way of executing things ? It seems lot easier that way.

./Rahul


minux

unread,
Dec 7, 2013, 12:55:58 AM12/7/13
to Rahul R, golang-nuts
Only when you don't need to handle spaces in filenames.

you can easily do what you want by using the shell, something like this:
exec.Command("sh", "-c", "g++ test.cpp -o test.o") // "cmd", "/c", "xxx" on windows

however, you will then meet the challenge of properly escaping the argument for the
shell, and trust me, that problem is much more complicated than option [1].

Coda Hale

unread,
Dec 7, 2013, 12:49:29 PM12/7/13
to Rahul R, golang-nuts
You’re better off keeping the arguments as separate strings, but it’s easy to pass a slice as a variadic argument:


This allows you to dynamically construct your argument list.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

signature.asc

Carlos Castillo

unread,
Dec 8, 2013, 3:28:33 AM12/8/13
to golan...@googlegroups.com
Option 1 is analogous to how the exec system call in unix works, which is generally portable to unixes, and easy to reproduce on the systems like windows.

Option 2 requires the existence of a specific shell executable, or such logic in the go std library. In the case of the former, you have inserted a dependency on an external application into the standard library. In the case of the latter, the std lib needs to include a command line parser, for no reason other than to allow the programmer to be lazy.

Since Option 1 is what exists, and you could do what minux suggests you really want the behaviour of #2, I don't see a problem. If you are bit by the mistake of assuming 2, you should be able to easily tell what you did wrong, and how to fix it. Option #2 is also less secure, as it allows for code injection similar to SQL and many programming languages' "eval" call.
Reply all
Reply to author
Forward
0 new messages