Golang操作命令行的幾種方式總結(jié)
前言
在實際開發(fā)工作中,我們經(jīng)常使用命令行進(jìn)行日志分析、程序部署、debug程序等工作。在Linux下,|、grep、find、xagrs、awk等工具是非常強(qiáng)大的,可以很容易的完成各種數(shù)據(jù)處理。在需求比較簡單的情況下,我們會直接命令行;如果再復(fù)雜一點,我們會編寫簡單的Shell腳本;如果業(yè)務(wù)更加復(fù)雜,shell已經(jīng)不適合進(jìn)行處理了,我們就會使用我們熟悉的語言進(jìn)行編碼,如果你剛好使用Golang,那么可以使用Golang內(nèi)置的exec.Command完成命令行操作。
簡單使用
func main() {
// # grep 321 2022053015.log
command := exec.Command("grep", "321", "2022053015.log")
out := bytes.NewBuffer(nil)
command.Stdout = out
command.Stderr = os.Stderr
if err := command.Run(); err != nil {
log.Fatal(err)
}
fmt.Println(out.String())
}上面的代碼是最簡單的一種使用命令行工具的方式,它會直接調(diào)用對應(yīng)工具的程序,然后獲取執(zhí)行結(jié)果。然而,如果像下面這樣包含通配符,是無法實現(xiàn)我們想要的效果的。因為通配符是Shell程序進(jìn)行處理的,而我們這里是直接調(diào)用grep程序,因此只會去查詢是否有精準(zhǔn)匹配20220530*.log名字的文件,不會展開*。
func main() {
// # grep 321 20220530*.log
command := exec.Command("grep", "321", "20220530*.log")
out := bytes.NewBuffer(nil)
command.Stdout = out
command.Stderr = os.Stderr
if err := command.Run(); err != nil {
log.Fatal(err)
}
fmt.Println(out.String())
}使用Shell執(zhí)行命令
為了能夠使用Shell的能力,我們需要先進(jìn)入Shell上下文,再輸入我們需要的命令。
func main() {
// 進(jìn)入Shell上下文
command := exec.Command("sh")
in := bytes.NewBuffer(nil)
out := bytes.NewBuffer(nil)
command.Stdin = in
command.Stdout = out
command.Stderr = os.Stderr
// 輸入命令,記得每個命令最后以換行符結(jié)束,這樣Shell才會執(zhí)行這個命令
grepCmd := fmt.Sprintf("grep %s %s*.log\n", "321", "20220530")
in.WriteString(grepCmd)
// 完成之后退出Shell上下文
in.WriteString("exit\n")
if err := command.Run(); err != nil {
log.Fatal(err)
}
fmt.Println(out.String())
}簡單封裝Shell執(zhí)行命令
上面的代碼核心只有grepCmd := fmt.Sprintf("grep %s %s*.log\n", "321", "20220530")這一行,其他的基本上都是模板代碼,因此最好簡單封裝一下,避免到處拷貝代碼。
// 執(zhí)行shell命令
func Exec(cmd string) (*bytes.Buffer, error) {
command := exec.Command("sh")
in := bytes.NewBuffer(nil)
out := bytes.NewBuffer(nil)
command.Stdin = in
command.Stdout = out
command.Stderr = os.Stderr
in.WriteString(cmd)
in.WriteString("exit\n")
return out, command.Run()
}
func main() {
grepCmd := fmt.Sprintf("grep %s %s*.log\n", "321", "20220530")
out, err := Exec(grepCmd)
if err != nil {
log.Fatal(err)
}
fmt.Println(out.String())
}到此這篇關(guān)于Golang操作命令行的幾種方式總結(jié)的文章就介紹到這了,更多相關(guān)Golang命令行操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
golang如何部署到服務(wù)器及應(yīng)注意問題解析
這篇文章主要為大家介紹了golang如何部署到服務(wù)器及應(yīng)注意問題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
go標(biāo)準(zhǔn)庫net/http服務(wù)端的實現(xiàn)示例
go的http標(biāo)準(zhǔn)庫非常強(qiáng)大,本文主要介紹了go標(biāo)準(zhǔn)庫net/http服務(wù)端,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
golang實現(xiàn)簡單的udp協(xié)議服務(wù)端與客戶端示例
這篇文章主要介紹了golang實現(xiàn)簡單的udp協(xié)議服務(wù)端與客戶端,結(jié)合實例形式分析了基于UDP協(xié)議的數(shù)據(jù)傳輸相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2016-07-07
Go中的函數(shù)選項模式(Functional Options Pattern)詳解
在 Go 語言中,函數(shù)選項模式是一種優(yōu)雅的設(shè)計模式,用于處理函數(shù)的可選參數(shù),本文將對其進(jìn)行講解,準(zhǔn)備好了嗎,快跟隨著本文一探究竟吧2023-06-06

