Reading user input

We use the read command to accept the user's input from the keyboard.

Example:

  1. Accepting a user's name

    #! /bin/bash
    echo "Enter your name: "
    read name
    echo "Hello there $name"
    

    In the above example the read command stores the input from the keyboard into the variable name.

  2. Accepting multiple inputs

    #! /bin/bash
    echo "Enter the names of your mother and father : "
    read father mother
    echo "Hello there Mr. $father and Mrs $mother"
    
    $ ./inputs.sh
    Enter the names of your mother and father : 
    Roger Rouge
    Hello there Mr. Roger and Mrs Rouge
    

    Don't press the enter key after entering the value into the first variable, instead press space and enter the value into the next variable.

  3. In the above two examples we can observe that the prompt text (Enter your name) and the input promt are on separate lines. If we want them to come on the same line we can use the read -p command.

    #! /bin/bash
    read -p  "Enter the names of your mother and father : " father mother
    echo "Hello there Mr. $father and Mrs $mother"
    
    $ ./hello-world.sh
    Enter the names of your mother and father : Roger Rouge
    Hello there Mr. Roger and Mrs Rouge
    
  4. To obscure the text during input then use the -s option

    #! /bin/bash
    read -sp "Enter your Password: " $password
    echo "Your password is: $password"
    
    $ ./obscure-text.sh
    Enter your Password: 
    Your password is: mypassword
    
  5. If no variable is given along with the read command then it stores it in the $REPLY variable by default.

    #! /bin/bash
    read 
    echo "Your text is: $REPLY"
    
    $ ./default-input.sh
    Hello 
    Your text is: Hello
    
  6. You can use read -a command to store the input in an array

    #! /bin/bash
    echo "Enter the names" 
    read -a names
    echo "Hello there ${names[0]} and ${names[1]}"
    
    $ ./array-input.sh
    Enter the names
    Dragon Luffy
    Hello there Dragon and Luffy
    

Passing arguments to a script