Golang: Operating System & I/O

Executing shell commands, script files, and executables in Go

In this article, we are going to learn how to execute external shell commands, script files and executable files from a Go program using built-in os/exec package

Uday Hiwarale
Published in
8 min readFeb 9, 2020

--

(source: unsplash.com)

While working with any programming language, you have to admit that not everything can be written in a program. Sometimes, you need to use external programs to perform some job that your program was not intended to do.

For example, to find the current user of the system, you can use whoami bash command that returns the username. You wouldn’t write a program to just find that out with complicated logic and OS dependencies.

💡 FYI, Go provides os/user package to get the information about the system users and user groups. You can use user.Current() function to get information about the current user of a system.

Sometimes, you have a program written in different languages like JavaScript or Bash that you want to execute from a Go program and read the output once the program finishes successfully.

If you are working with Node.js, then you are familiar with child_process built-in package. In Go, we have…

--

--