【问题标题】:In bash, how to process all user input on command line在 bash 中,如何处理命令行上的所有用户输入
【发布时间】:2016-01-12 22:40:58
【问题描述】:

如何将命令行上的所有用户输入作为程序的标准输入?

就我而言,我想替换用户输入的某些单词。例如,每次用户使用单词animal1,我希望它接收为goldfish。所以它看起来像这样:

$ animal1
goldfish: command not found

我尝试了以下 bash 命令

while read input
do
   sed "s/animal2/zebra/g;s/animal1/goldfish/g" <<< "$input"
done

但它会提示用户输入并且不会返回到 bash。我希望它在使用 bash 命令行时运行。

此外,这使我只能捕获输出。

bash | sed 's/animal2/zebra/g;s/animal1/goldfish/g'

但不是用户输入。

【问题讨论】:

    标签: bash input sed stdin


    【解决方案1】:

    如果我理解正确,听起来你只需要设置一些别名:

    $ alias animal1=goldfish
    $ animal1
    bash: goldfish: command not found
    

    这允许 shell 像往常一样以交互方式使用,但会进行您想要的替换。

    您可以将此别名定义添加到您的启动文件之一,通常是~/.bashrc~/.profile,以使它们在您打开的任何新shell 上生效。

    【讨论】:

      【解决方案2】:

      Tom Fenech 提供的解决方案很好,但是,如果您打算在命令中添加更多功能,您可以使用如下函数:

      animal1() {
          echo "Welcome to the new user interface!"
          goldfish
          # other commands
      }
      

      并将其放入用户~/.bashrc~/.bash_profile

      输出将是:

      $>animal1 
      Welcome to the new user interface!
      -bash: goldfish: command not found
      

      例如,通过使用这种方法,您可以创建自定义输出消息。在下面的 sn-p 中,我从命令中获取返回值并逐字处理它。然后我删除输出的-bash: 部分并重构消息并输出它。

      animal1() {
          echo "Welcome to the new user interface!"
          retval=$(goldfish 2>&1)
          # Now retval stores the output of the command glodfish (both stdout and stderr)
          # we can give it directly to the user
          echo "Default return value"
          echo "$retval"
          echo
          # or test the return value to do something
          # here I build a custom message by removing the bash part 
          message=""
          read -ra flds <<< "$retval"
          for word in "${flds[@]}" #extract substring from the line
              do
                  # remove bash
                  msg="$(echo "$word" | grep -v bash)"
                  # append each word to message
                  [[ msg ]] && message="$message $msg"
              done
          echo "Custom message"
          echo "$message"
          echo
      }
      

      现在输出将:

      Welcome to the new user interface!
      Default return value
      -bash: goldfish: command not found
      
      Custom message
        goldfish: command not found
      

      如果您注释与默认返回值相呼应的行,那么您将得到您所要求的输出。

      【讨论】:

      • 哦,太好了!谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 2016-09-04
      • 2019-01-24
      • 2014-04-04
      • 2014-03-28
      • 1970-01-01
      相关资源
      最近更新 更多