Use the bash autocomplete with [TAB] from within a script where the input is in a variable

346 views Asked by At

I have a bash script that asks the user for them to type in a file name. I want the script to accept partial file name such as /b, and the script should output a list of files that includes every file that matches that partial name. For Example:

there are files named
animal
bat
boo
bury
in /

typing /b should then result in bat boo bury. If a user enters /animal/c the program should result in all files starting with a c in the animal folder.

Essentially I am trying to get the effect of [TAB] with a static input inside a script.

Thanks for the help!

1

There are 1 answers

1
that other guy On BEST ANSWER

Don't use tab completion. Use globs. /b* will match /bat, /boo and /bury if these files or directories exist.

#!/bin/bash 
shopt -s nullglob
IFS= read -p "Enter a full or partial name: " -r filename
for f in "$filename"*
do
    echo "Possible match: $f" 
done