いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-198 (*exec.Cmd 実行時にワーキングディレクトリを指定する)

概要

以下自分用のメモです。よく忘れるのでここにメモメモ。。。

外部コマンド実行時に特定のディレクトリをワーキングディレクトリにして開始したい場合があります。

その場合は (*exec.Cmd).Dir に値を設定することで可能となります。

サンプル

package cmdexec

import (
    "errors"
    "os"
    "os/exec"
    "runtime"

    "github.com/devlights/gomy/output"
)

// WithDir -- *exec.Cmd 実行時にワーキングディレクトリを指定するサンプルです.
//
// REFERENCES
//  - https://dev.to/tobychui/quick-notes-for-go-os-exec-3ejg
func WithDir() error {
    if runtime.GOOS == "windows" {
        return errors.New("this example cannot run on Windows, sorry")
    }

    const (
        Shell = "/bin/bash"
    )

    var (
        cmd *exec.Cmd
        out []byte
        err error
    )

    output.Stdoutl("[cwd]", func() string { c, _ := os.Getwd(); return c }())

    //
    // プロセス実行時のワーキングディレクトリの指定なし
    //
    cmd = exec.Command(Shell, "-c", "pwd")

    out, err = cmd.Output()
    if err != nil {
        return err
    }

    output.Stdoutf("[no dir]", "%s", out)

    //
    // プロセス実行時のワーキングディレクトリの指定あり
    //
    cmd = exec.Command(Shell, "-c", "pwd")
    cmd.Dir = "/tmp"

    out, err = cmd.Output()
    if err != nil {
        return err
    }

    output.Stdoutf("[with dir]", "%s", out)

    return nil
}

実行すると以下のようになります。

gitpod /workspace/try-golang (master) $ make run
go run -race main.go -onetime -example ""

ENTER EXAMPLE NAME: cmdexec_dir

[Name] "cmdexec_dir"
[cwd]                /workspace/try-golang
[no dir]             /workspace/try-golang
[with dir]           /tmp


[Elapsed] 3.155899ms

参考情報


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。