linuxbashshell

What is the purpose of `-i` in `read` in bash? How do you use it?


I thought this:

read -p "Make this rsync backup session a dry run [Y/n]? " -i '--dry-run' dry_run
echo "$dry_run"

...would output --dry-run as its "default value" if I just hit Enter to reply to the prompt. But, it doesn't. It outputs a newline.

What is the purpose of -i and how does it work?

From help read:

-i text   use TEXT as the initial text for Readline

For anyone who wants to see where I learned how to make a bash prompt to the user: How do I read user input into a variable in Bash?


Solution

  • The -i option only works together with the -e option to enable using Readline, and it prefills its contents on the prompt:

    read -e -p "Prompt: " -i 'initial-text'
    

    prints this prompt:

    Prompt: initial-text
    

    where the initial-text part is editable.

    For your example:

    read -ep "Make this rsync backup session a dry run [Y/n]? " -i '--dry-run'
    

    resulting in

    Make this rsync backup session a dry run [Y/n]? --dry-run
    

    and --dry-run part is editable.