bash - 是否可以对 bash 自动完成输出进行分类?
问题描述
我已经阅读了GNU 网站上的bash 可编程完成,以及关于stackoverflow和unix.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
解决方案
推荐阅读
- python - 元组对象不是可调用问题。(简单鳕鱼)
- python - Scrapy在身份验证后抓取每个链接
- mysql - 如何针对数组在表中搜索json编码的数组列并返回匹配结果?
- java - 基于字符偏移的动态重新定位的字符阅读器(如 FileReader)
- javascript - JavaScript 日期元素显示为第二天而不是当天
- excel - 将数据从 excel 复制到现有的 powerpoint 图表
- javascript - 使用 .select jquery 但没有得到任何选定的文本
- javascript - HTML5 直接从 Safari iOS 上的照片库中选择照片
- python - Python中的df_dict
- kivy - 在 RecyleView kivy 中添加 KivyMD 扩展面板