github.com/xyproto/u-root@v6.0.1-0.20200302025726-5528e0c77a3c+incompatible/pkg/sh/run.go (about)

     1  // Copyright 2018 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package sh
     6  
     7  import (
     8  	"log"
     9  	"os"
    10  	"os/exec"
    11  )
    12  
    13  // Run runs a command with stdin, stdout and stderr.
    14  func Run(arg0 string, args ...string) error {
    15  	return RunWithIO(os.Stdin, os.Stdout, os.Stderr, arg0, args...)
    16  }
    17  
    18  // RunWithLogs runs a command with stdin, stdout and stderr. This function is
    19  // more verbose than log.Run.
    20  func RunWithLogs(arg0 string, args ...string) error {
    21  	log.Printf("executing command %q with args %q", arg0, args)
    22  	err := RunWithIO(os.Stdin, os.Stdout, os.Stderr, arg0, args...)
    23  	if err != nil {
    24  		log.Printf("command %q with args %q failed: %v", arg0, args, err)
    25  	}
    26  	return err
    27  }
    28  
    29  // RunWithIO runs a command with the given input, output and error.
    30  func RunWithIO(in, out, err *os.File, arg0 string, args ...string) error {
    31  	cmd := exec.Command(arg0, args...)
    32  	cmd.Stdin = in
    33  	cmd.Stdout = out
    34  	cmd.Stderr = err
    35  	return cmd.Run()
    36  }
    37  
    38  // RunOrDie runs a commands with stdin, stdout and stderr. If there is a an
    39  // error, it is fatally logged.
    40  func RunOrDie(arg0 string, args ...string) {
    41  	if err := Run(arg0, args...); err != nil {
    42  		log.Fatal(err)
    43  	}
    44  }