Foil 07 - Utility subroutine to ask for user input (1/2)

 1 #*********************************************************************
 2 # Function to ask the user a question and return the response.       *
 3 #                                                                    *
 4 # The first parm is the prompt string.  The second is an optional    *
 5 # default value used if the user does not supply a value.  If there  *
 6 # is no default, the user is prompted until a value is supplied.     *
 7 # The result is returned in variable input_value.                    *
 8 #*********************************************************************
 9 input() {
10 
11 input_value=
12 prompt_string="$1"
13 default_value="$2"
14 
15 if [ "$2" != "" ]
16   then
17     default="$default_value"
18   else
19     default="No Default"
20   fi                                                               #07

This is the first half of a subroutine to ask the user a question and ask for a response. The question is output along with an optional default value used if the carriage return is pressed. The cursor is left on the same line and an input is read. If there is no default, it loops until the user supplies a value.

  • Line 11 initializes the returned value to a null string.
  • Lines 12 and 13 parse the subroutine arguments.
  • Lines 15-20 set the default value based on the optional second argument.

    Previous   Next   Index