golang中實現linux管道

在linux中通過管道能夠讓一個命令的輸出變為另一個命令的輸入,下面是一個典型的例子:

<code>> cat words | sort | uniq

apple

bye

hello

zebra/<code>

下面我們來用golang實現一個簡單的命令:將輸入都變為大寫字母,效果如下:

<code>> cat words | sort | uniq | uppercase

APPLE

BYE

HELLO

ZEBRA/<code>

我們需要實現uppercase命令,能夠正確的識別出管道,本次我們命令的骨架使用Cobra。


第一步:創建命令

<code>var rootCmd = &cobra.Command{

Use:"uppercase",

Short: "Transform the input to uppercase letters",

Long: `Simple demo of the usage of linux pipes

Transform the input (pipe of file) to uppercase letters`,

RunE: func(cmd *cobra.Command, args []string) error {

print = logNoop


if flags.verbose {

print = logOut

}

return runCommand()

},

}/<code>

採用Cobra框架,RunE是命令執行會返回err,命令的主體邏輯都在runCommand中。

第二步:判斷是否是在管道:

<code>func isInputFromPipe() bool {

fi, _ := os.Stdin.Stat()

return fi.Mode()&os.ModeCharDevice == 0

}/<code>

第三步:主體邏輯,將小寫轉為大寫:

<code>func toUppercase(r io.Reader, w io.Writer) error {

scanner := bufio.NewScanner(bufio.NewReader(r))

for scanner.Scan() {

_, e := fmt.Fprintln(

w, strings.ToUpper(scanner.Text()))

if e != nil {

return e

}

}

return nil

}/<code>

以上就是全部邏輯,完整的代碼可以查看:

go-linux-pipes

總結

  1. 命令行程序可以使用Cobra
  2. 如何判斷是否是從管道讀取


分享到:


相關文章: