18
14

More than 5 years have passed since last update.

Go言語で一時的にカレントディレクトリを変更する。

Last updated at Posted at 2014-05-14
package main

import (
    "os"
    "path/filepath"
)

func main() {
    .
    .

    // 現在のディレクトリを保存してからcd
    prevDir, _ := filepath.Abs(".")
    os.Chdir(root)

    // ここでやりたい処理を書く     
    // ….

    // 元に戻す
    os.Chdir(prevDir)

    .
    .
}

// 関数スコープなら defer を使った方が綺麗に書ける
func cd(dir string) {
    // あらかじめ戻り先を絶対パスに展開しておく
    prev, err := filepath.Abs(".")
    if err != nil {
        return // ERROR
    }
    defer os.Chdir(prev)

    // ディレクトリ移動
    os.Chdir(dir)

    .
    .
    if xxxx {
        return // ここでも呼ばれるし
    }

    .
    .
    // ここでも呼ばれる
}
18
14
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
14