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

StackOverflow https://stackoverflow.com/questions/20436302

  •  30-08-2022
  •  | 
  •  

Question

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!

Était-ce utile?

La solution

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top