Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre-filling a prompt in Bash

Tags:

bash

Writing a bash script, and I want to get user input. Awesome,

read -p "What directory should we save in? " -e FOLDER

Except that what I'd like to do, ideally, is have the user see something like:

What directory should we save in? /home/user/default/

with the cursor at the end of the line, and the ability to delete backwards or append or whatever. Essentially, pre-filling the user's input, but giving them the ability to edit it.

Readline obviously has the capability, but it appears to be not exposed in the read command. Any alternatives? I'd prefer to not have to use perl or such.

The constraint I'm working under is that I'm writing a single shell script that would be nice to disseminate widely, so should rely on as little pre-existing infrastructure as possible. rlwrap and read -i both work if their dependencies (rlwrap and bash version >> whatever I have, respectively) are available. Both good answers, choose whichever works for you.

like image 478
agnoster Avatar asked Feb 17 '11 13:02

agnoster


People also ask

What does #$ mean in bash?

#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications.

How do you ask for input in bash?

If we would like to ask the user for input then we use a command called read. This command takes the input and will save it into a variable.

How do I change the $ps1 prompt in Linux bash?

You can change the BASH prompt temporarily by using the export command. This command changes the prompt until the user logs out. You can reset the prompt by logging out, then logging back in.


1 Answers

$ read -p "What directory should we save in? " -i "/home/user/default/" -e FOLDER
What directory should we save in? /home/user/default/

that should work, right?

like image 150
vmpstr Avatar answered Sep 20 '22 05:09

vmpstr