【问题标题】:getting interactive, multiple line, formatted input from stdin in bash在 bash 中从标准输入获取交互式、多行、格式化输入
【发布时间】:2019-08-27 13:41:02
【问题描述】:

我希望能够以类似于 hereDOC 的方式从终端交互式获取输出。即我希望用户能够键入多行,然后将该信息传递到一个文件中,并保留所有格式。像这样的。

echo  "Type your message below. To finish the letter type DONE by itself on a line"
file=mktmp
cat << DONE > $file

显然这不起作用,因为 EOF 是在 DONE 之前找到的。我考虑过将用户传递给 VIM 之类的东西,但我不太懂电脑的同事很难使用 vim/emacs/nano。

【问题讨论】:

  • 使用$EDITOR,你的同事可以设置EDITOR=their-editor-of-choice
  • 直接从标准输入读取将远不如任何编辑器对用户友好。

标签: bash user-interface stdin


【解决方案1】:

好的,所以我想出了这个,但请帮助我找到更好的东西或改进它。

echo  "Type your message below, to finish the letter press CTL+D"
mapfile message
file=`mktemp`
for x in `seq 0 ${#message[@]}`
        do printf "${message[$x]}" >> $file
done
cat $file

【讨论】:

    【解决方案2】:

    您需要使用编辑器;标准输入只是一个字节流,而不是编辑器。但是,您不必对特定的编辑器进行硬编码。 EDITOR 是一个标准环境变量,旨在允许脚本的调用者选择使用哪个编辑器。

    : ${EDITOR:?Please set the environment variable EDITOR to the editor of your choice}
    echo "Type your message below, then save and exit your editor."
    "$EDITOR" "$file"
    

    EDITOR 通常由用户在其 shell 配置文件中设置,但可以在运行脚本时按需设置。

    $ EDITOR=nano yourScript.sh
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多