【问题标题】:How do i make a function in my .bash_profile accept input from stdin using pipe | [duplicate]如何使我的 .bash_profile 中的函数使用管道接受来自标准输入的输入 | [复制]
【发布时间】:2020-09-15 18:53:55
【问题描述】:

假设我的 .bash_profile 中有这种性质的功能

sayword(){
   echo $1
}

现在命令将像sayword hello一样运行 现在我希望该函数能够使用 unix 管道从其他命令中获取输入。类似cat words.txt | sayword 的东西,它会输出words.txt 中的每个单词。我怎么做 ?。我在这里阅读了一个关于重定向到 dev/null 的问题,但这似乎不起作用。

【问题讨论】:

    标签: linux bash unix


    【解决方案1】:

    这是您想要-t 条件的地方:可以测试标准输入是管道/重定向还是终端(即交互式):

    sayword() {
      {
        echo "$(date) - saying words"
        if [ -t 0 ]; then
          # stdin is the terminal: take input from the cmdline parameters:
          echo "$*"
        else
          # stdin is a pipe or redirection
          cat
        fi
      } >> "$HOME/words.txt"
    }
    

    然后,这些都附加到文件中:

    $ sayword hello
    $ cat ~/words.txt
    Thu May 28 09:22:27 EDT 2020 - saying words
    hello
    
    $ echo foo bar | sayword
    $ cat ~/words.txt
    Thu May 28 09:22:27 EDT 2020 - saying words
    hello
    Thu May 28 09:22:37 EDT 2020 - saying words
    foo bar
    

    【讨论】:

      【解决方案2】:

      你可以这样写

      function sayword() {
        if [ $# -eq 0 ]
        then
          while read input; do
            echo $input
          done
        else
          echo $1
        fi
      }
      

      然后你可以这样称呼它

      date | sayword
      

      【讨论】:

      • 虽然这很有帮助,但看起来我可以这样称呼它```sayword hello```了,我需要这种灵活性。无论如何,我很感激你的回答,非常感谢
      • 我编辑了我的答案以满足您的需求,检查它是否有帮助
      • 如果你把它称为sayword 1 2 3,它只会重复1。如果您希望所有输入都集中在一行上,请使用echo "$@"。如果您希望它们在单独的行上输出,请使用printf "%s\n" "$@"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      • 2019-12-17
      • 1970-01-01
      • 2020-07-23
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多