58

Inside my Bash script, I'm reading some variables entered by the user with read:

read -p "Glassfish Path:" GF_DIR

Now I want that the user gets a autocompletion when he has to enter a directory, like when you are on the Bash shell. So when he enters the first letters of a directory, he can autocomplete it by hitting TAB. Is that possible?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Wolkenarchitekt
  • 20,170
  • 29
  • 111
  • 174

1 Answers1

96

Try:

read -e -p "Glassfish Path:" GF_DIR

-e enables readline:

 -e 
    If the standard input is coming from a terminal, Readline is used
    to obtain the line.
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
miku
  • 181,842
  • 47
  • 306
  • 310
  • 1
    Sorry, should have read the manpage. Thought it's not that easy ;) – Wolkenarchitekt Jan 27 '11 at 18:12
  • 1
    I've looked all over the interwebs, and taken many wrong turns with bash `complete`... yet it really was this easy the whole time. Thanks! – Lindsey D Feb 08 '15 at 23:22
  • 12
    How do I get it to respect custom completions? That is, I have things set up so that, on the normal prompt, git branch names are completed. But when I use readline -e it's only completing file names. – Max Heiber Feb 16 '17 at 23:01
  • 1
    @MaxHeiber Have never found a sane way to do that; though for some interactive scripts I create a temporary directory with `mktemp --tmpdir -d foo.XXXXXXXX`, cd to it and touch files with the options, commands etc. I want to have completion on ... This then works nice with `-e`. Only have to be careful about being in correct directory when doing touch, rm etc ;) – user3342816 Oct 09 '21 at 11:28