Read a variable in bash with a default value

后端 未结 9 638
不思量自难忘°
不思量自难忘° 2020-11-29 16:13

I need to read a value from the terminal in a bash script. I would like to be able to provide a default value that the user can change.

# Please enter your          


        
9条回答
  •  一生所求
    2020-11-29 16:57

    In Bash 4:

    name="Ricardo"
    read -e -i "$name" -p "Please enter your name: " input
    name="${input:-$name}"
    

    This displays the name after the prompt like this:

    Please enter your name: Ricardo
    

    with the cursor at the end of the name and allows the user to edit it. The last line is optional and forces the name to be the original default if the user erases the input or default (submitting a null).

提交回复
热议问题