不能用 Go 跑 mysqldump 匯出資料庫?

Kettan Wu
Kettan Wu
Jul 20, 2017 · 1 min read

有個需求是定期匯出資料庫,要用 Go 實作。

本來的寫法是這樣:

// $ mysqldump myDB > mydb.sql
err := exec.Command("mysqldump", "myDB", ">", "mydb.sql").Run()

結果跑起來 mysqldump 會一直抱怨 cannot find database ">" (之類的,憑印象打出來的錯誤訊息)

後來想到 > 是 shell 在用的語法,Go 不是呼叫 shell 跑指令。

改成這樣就可以如預想運作了:

cmd := strings.Join([]string{"mysqldump", "myDB", ">", "mydb.sql"}, " ")
err := exec.Command("sh", "-c", cmd).Run()

)

guá sī tsi̍t ê kang-tîng-su

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade