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

Share:
7,720

Related videos on Youtube

Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    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
    Neo almost 11 years
    Thanks! 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
    Neo almost 11 years
    It does work in Debian, which is where I plan to use it. :)
  • Angel Todorov
    Angel Todorov almost 11 years
    you probably have an older version of bash on your mac: echo $BASH_VERSION
  • Stéphane Chazelas
    Stéphane Chazelas almost 11 years
    The -i flag was added in bash 4.0. help '[r]ead' to get the help for read only. Note that while read -e will be able to complete inside ~, it will not be expanded.
  • Neo
    Neo almost 11 years
    Thanks Stephane. What does that mean? (Probably (certainly) a stupid question.)
  • Angel Todorov
    Angel Todorov almost 11 years
    It means you'll get the literal tilde in the $path variable, which may be difficult to handle. In hindsight, use -i "$HOME/x/"
  • dodgethesteamroller
    dodgethesteamroller almost 11 years
    If you want to have bash 4.x on OS X, it's only as far away as homebrew :)