Use the terminal's autocomplete path feature for input to a shell script
7,720
read -p "enter a directory: " -i "$HOME/x/" -e path
From a bash session, enter help read|less
Related videos on Youtube
Author by
Admin
Updated on September 18, 2022Comments
-
Admin over 1 year
I want to make a script that: (1) Gets a path giving the user the ability to use tab to autocomplete, then (2) gets a filename from the user, and then (3) creates a file at that path with extension .txt.
My question is: How do I do 1.? How do I tell bash to ask for input that is an "autocompletable" path, preferably with part of the path (say ~/x/) already filled out by default?
Note: the paths will almost always include spaces.
-
Neo almost 11 yearsThanks! On osx I get this error: "-bash: read: -i: invalid option read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]" Is this an osx thing?
-
Neo almost 11 yearsIt does work in Debian, which is where I plan to use it. :)
-
Angel Todorov almost 11 yearsyou probably have an older version of bash on your mac:
echo $BASH_VERSION
-
Stéphane Chazelas almost 11 yearsThe
-i
flag was added inbash
4.0.help '[r]ead'
to get the help forread
only. Note that whileread -e
will be able to complete inside~
, it will not be expanded. -
Neo almost 11 yearsThanks Stephane. What does that mean? (Probably (certainly) a stupid question.)
-
Angel Todorov almost 11 yearsIt means you'll get the literal tilde in the $path variable, which may be difficult to handle. In hindsight, use
-i "$HOME/x/"
-
dodgethesteamroller almost 11 yearsIf you want to have
bash
4.x on OS X, it's only as far away ashomebrew
:)