Question

How can I use bash tab completion on a fixed directory within a script? Suppose I have a directory ~/pdf containing pdf-files. I want to make a simple script to view these files, e.g. viewpdf:

#! /bin/bash

evince $1

Let say I am in directory ~/foo/bar and write viewpdf ~/pdf/test.pdf, I can then view the file. However, I would like to use bash tab completion on the ~/pdf directory, such that viewpdf t <tab><tab> would produce the same result. How can this be done?

Was it helpful?

Solution 2

Based on jm666's suggestion and the link provided by Kevin I now got the following code to work:

_cmd() { 
    local cur files
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    files=$(ls ~/pdf/) 
    COMPREPLY=( $(compgen -W "${files}" -- ${cur}) )
}

Note that ls ~/pdf/*.pdf does not work since it expands to pathname and not filename of each file..

OTHER TIPS

As 1st approximation, you can try next

_cmd() { COMPREPLY=($(ls ~/pdf/*.pdf)); }    
complete -F _cmd viewpdf

source it and you can use

viewpdf <tab> #and will get the list of pdf files from the ~/pdf

if you want simple pdf competition,

complete -f -X '!*.@(pdf|PDF)' viewpdf
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top