【问题标题】:How can a shell script get input from an external editor (like Git does)?shell 脚本如何从外部编辑器(如 Git)获取输入?
【发布时间】:2015-02-24 20:27:46
【问题描述】:

我想要一个 shell 脚本暂停,从外部编辑器获取输入,然后恢复。像这样的伪代码,作为一个最小的例子:

testScript(){
  content=""
  # set value of content using vim...
  echo "$content"
}

我不想使用包,只是 Bash。

【问题讨论】:

  • 在已知文件名上启动$EDITOR
  • 所以我想这应该是一个临时文件,对吧?我在这里玩过,但不确定如何使它工作,有什么建议吗?
  • 是的,为了安全起见,您可能需要一个临时文件名。看mktemp

标签: git bash shell vim


【解决方案1】:
#!/bin/bash

# This uses EDITOR as editor, or vi if EDITOR is null or unset
EDITOR=${EDITOR:-vi}

die() {
    (($#)) && printf >&2 '%s\n' "$@"
    exit 1
}

testScript(){
  local temp=$(mktemp) || die "Can't create temp file"
  local ret_code
  if "$EDITOR" -- "$temp" && [[ -s $temp ]]; then
      # slurp file content in variable content, preserving trailing blank lines
      IFS= read -r -d '' content < "$temp"
      ret_code=0
  else
      ret_code=1
  fi
  rm -f -- "$temp"
  return "$ret_code"
}

testScript || die "There was an error when querying user input"
printf '%s' "$content"

如果您不想保留尾随空行,请替换

IFS= read -r -d '' content < "$temp"

content=$(< "$temp")

您还可以添加一个陷阱,以便在临时文件创建和删除之间脚本停止的情况下删除临时文件。

我们正在努力检查整个过程是否一切正常:

  • 如果我们无法创建临时文件,函数 testScript 会提前中止;
  • 当我们编辑临时文件时,我们检查编辑器是否正常运行和结束,然后我们还通过使用[[ -s $temp ]] 检查文件是否存在且不为空来明确检查用户是否输入了至少一个字符。
  • 我们使用内置的read 将文件添加到变量内容中。使用这种方式,我们不会修剪任何前导或尾随空白,也不会修剪尾随换行符。变量content 包含尾随换行符! 你可以用${content%$'\n'} 修剪它;另一种可能性是完全不使用read,而是使用content=$(&lt; "$temp")
  • 我们在继续之前明确检查函数返回时没有错误。

【讨论】:

    【解决方案2】:

    小猪放弃了 Etan Reisner 的建议,您可以设置一个 /tmp 文件用于编辑。然后读入内容。除非该文件将用于在脚本的其他部分聚合某些数据,否则您可能希望在设置完 $content var 后清除内容。

    testScript() {
      content=""
      contentFile=/tmp/input
      vim $contentFile
      content=`cat $contentFile`
      cat /dev/null > $contentFile
    }
    
    testScript
    echo $content
    

    【讨论】:

    • 为避免来自并行实例的冲突,您可能希望在文件名中包含 shell 的进程 ID ($$) - 或者更好的是,使用 mktemp(1)
    猜你喜欢
    • 2014-12-23
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    相关资源
    最近更新 更多