首页 > 解决方案 > 是否可以对 bash 自动完成输出进行分类?

问题描述

我已经阅读了GNU 网站上的bash 可编程完成,以及关于stackoverflowunix.stackexchange.com的许多很好的问答。幸运的是,我制作了一个自动完成脚本,几乎可以完全按照我的意愿工作。但是,我需要对建议进行格式化。

有没有办法根据它们的类型对建议进行分类。例如,我想要这样的东西:

$ foo --bar # press TAB twice and get the result as below:
* Directories:
foo/   bar/   baz/
* Files:
foo.sh   bar.sh   baz.sh
* Options:
--foo=   --bar   --baz

而不是这个:

$ foo --bar # press TAB twice and get the result as below:
--bar      --baz      --foo=      bar/      baz/
foo/       bar.sh     baz.sh      foo.sh

完成脚本的最小代码片段是:

_foo(){

   COMPREPLY=()
   local word="$2"
   local prev="$3"

   # Suggest directories
   COMPREPLY+=( $( compgen -d -- $word ) )
   
   # Suggest '*.sh' files with negating the '-X' filter pattern
   COMPREPLY+=( $( compgen -f -X "![.][sS][hH]$" -- $word ) )

   # Suggest options in the '-W' word list
   COMPREPLY+=( $( compgen -W "--foo= --bar --baz" -- $word ) )
}

complete -F _foo foo

感谢您的时间、想法和见解:)

更新:

我调整了@Socowi 的答案,这样额外的\就不会出现在=标志之前。

compgenSection() {
  title="* $1:"
  shift
  local entries
  mapfile -t entries < <(compgen "$@")
  (( "${#entries[@]}" == 0 )) && return
  COMPREPLY_SECTIONLESS+=("${entries[@]}")
  mapfile -tO "${#COMPREPLY[@]}" COMPREPLY < <(
    printf "%$((-COLUMNS/2))s\\n" "$title"
    printf %s\\n "${entries[@]}" | sort | column -s $'\n' | expand
  )
  [[ "${COMPREPLY[@]}" =~ "=" ]] && compopt -o nospace
}   
_foo(){
  local word="$2"
  COMPREPLY_SECTIONLESS=()
  compgenSection Directories -d -S / -- "$word"
  compgenSection Files -f -X '!*.[sS][hH]' -- "$word"
  compgenSection Options -W '--foo= --bar --baz' -- "$word"
  (( "${#COMPREPLY_SECTIONLESS[@]}" <= 1 )) &&
  COMPREPLY=("${COMPREPLY_SECTIONLESS[@]}")
}
complete -o nosort -F _foo foo

标签: bashautocompleteformatting

解决方案



推荐阅读