bash - How to complete filenames relative to another directory? -
this follow-up question discussion in:
https://bugs.launchpad.net/ubuntu/+source/bash-completion/+bug/1394920
suppose have folder ~/tmp
files , directories:
$ mkdir a; touch file1.txt; mkdir a/b; mkdir a/c; touch a/d; mkdir a/b/c
i try make completion script complete filenames in ~/tmp
, complete -o filenames
option working correctly if current directory ~/tmp
.
see above link more background information. far got:
$ cat setup _comptest() { local cur basefolder cur="${comp_words[$comp_cword]}" basefolder=~/tmp compopt -o nospace compreply=( $( cd "$basefolder" if [[ ${cur: -1} != "/" && -d $cur ]] ; echo "$cur/" else compgen -f "$cur" fi ) ) } complete -f _comptest aaa
then source it:
$ . setup
and can
$ aaa <tab><tab>
problem 1 : slashes not added @ end of directory names in completion list ( desired easy separate directories file names in completion list)
problem 2 :
aaa a/<tab><tab>
completion lista/b a/c a/d
a/
prefix should not there. shouldb/ c/ d
instead.
i write function as:
_comptest () { local cur; local tmp; local tmp_escaped; local i; _get_comp_words_by_ref cur; local _compreply=() tmp=~/tmp/ tmp_escaped=${tmp//\//\\\/} cur=$tmp$cur; if [ "$1" == "-d" ]; _cd else _filedir; fi; in "${compreply[@]}"; [ -d "$i" ] && [ "$i" != "$tmp." ] && [ "$i" != "$tmp.." ] && i="$i/" _compreply=("${_compreply[@]}" "$i") done compreply=(${_compreply[@]/$tmp_escaped/}) } && complete -o nospace -f _comptest aaa_files _comptestdir() { _comptest -d } && complete -o nospace -f _comptestdir aaa_directories
it has 3 parts,
- prefixing
$cur
base directory - ~/tmp. - using standard bash completion routine
_filedir
used cd/ls etc. - removing
~/tmp
compreply
just record: can use logic complete file names relative many other types of path, e.g.
- i use complete perforce paths
//...
. - you can complete
http://localhost/*
paths, relativepublic_html
directory.
Comments
Post a Comment