Code with Go
About
  • Code With Go! 🚀
  • Hello World
  • Values
  • Variables
  • Constants
  • For Loop
  • If Else
  • Switch
  • Array
  • Slice
  • Map
  • Range
  • Functions
  • Multiple Return Values
  • Variadic Functions
  • Closure
  • Recursion
  • Pointers
  • Strings and Runes
  • Structs
  • Methods
  • Interfaces
  • Struct Embedding
  • Generics
  • Error
  • Goroutines
  • Channels
  • Channel Buffering
  • Channel Synchronization
  • Channel Directions
  • Select
  • Timeouts
  • Non-Blocking Channel Operations
  • Closing Channels
  • Range over Channels
  • Timers
  • Tickers
  • Worker Pools
  • Wait Groups
  • Rate Limiting
  • Atomic Counters
  • Mutexes
  • Stateful Goroutines
  • Sorting
  • Sorting by Functions
  • Panic
  • Defer
  • Recover
  • String Functions
  • String Formatting
  • Text Templates
  • Regular Expressions
  • JSON
  • XML
  • Time
  • Epoch
  • Time Formatting / Parsing
  • Random Numbers
  • Number Parsing
  • SHA256 Hashes
  • Base64 Encoding
  • Reading Files
  • Writing Files
  • Line Filters
  • File Paths
  • Directories
  • Temporary Files and Directories
  • Embed Directive
  • Testing and Benchmarking
  • Command-Line Arguments
  • Command-Line Flags
  • Command-Line Subcommands
  • Environment Variables
  • Logging
  • HTTP Client
  • HTTP Server
  • Context
  • Spawning Processes
  • Exec'ing Processes
  • Signals
  • Exit
  • Resize Image
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub

Spawning Processes

This code is a Go program that demonstrates executing shell commands from Go using the os/exec package. Here's a breakdown of the code:

package main

import (
	"fmt"
	"io"
	"os/exec"
)

func main() {
	// Command: date
	dateCmd := exec.Command("date")
	dateOut, err := dateCmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Println("> date")
	fmt.Println(string(dateOut))

	// Command: date -x (intentionally invalid command)
	_, err = exec.Command("date", "-x").Output()
	if err != nil {
		switch e := err.(type) {
		case *exec.Error:
			fmt.Println("failed executing:", err)
		case *exec.ExitError:
			fmt.Println("command exit rc =", e.ExitCode())
		default:
			panic(err)
		}
	}

	// Command: grep hello
	grepCmd := exec.Command("grep", "hello")
	grepIn, _ := grepCmd.StdinPipe()
	grepOut, _ := grepCmd.StdoutPipe()
	grepCmd.Start()
	grepIn.Write([]byte("hello grep\ngoodbye grep"))
	grepIn.Close()
	grepBytes, _ := io.ReadAll(grepOut)
	grepCmd.Wait()
	fmt.Println("> grep hello")
	fmt.Println(string(grepBytes))

	// Command: ls -a -l -h
	lsCmd := exec.Command("bash", "-c", "ls -a -l -h")
	lsOut, err := lsCmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Println("> ls -a -l -h")
	fmt.Println(string(lsOut))
}

Explanation:

  1. The program demonstrates running various shell commands (date, date -x, grep hello, and ls -a -l -h) using the exec.Command function.

  2. The Output method is used to capture the standard output of the commands.

  3. For the grep hello command, the program demonstrates how to provide input to the command using StdinPipe.

  4. The program also shows how to handle errors and exit codes of the executed commands.

  5. The last command runs ls -a -l -h using bash -c to execute a shell command with arguments.

Please note that executing arbitrary commands obtained from user input can pose security risks (command injection). Always validate and sanitize user inputs before using them in command execution.

PreviousContextNextExec'ing Processes

Last updated 1 year ago

Was this helpful?