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!

Was it helpful?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top