Search code examples
bashshellinput

How do I read user input into a variable in Bash?


How do I read user input into a variable in Bash?

fullname=""
# Now, read user input into the variable `fullname`.

Solution

  • Use read -p:

    # fullname="USER INPUT"
    read -p "Enter fullname: " fullname
    # user="USER INPUT"
    read -p "Enter user: " user
    

    If you like to get the user's confirmation:

    read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
    

    You should also quote your variables to prevent filename expansion and word splitting with spaces:

    # passwd "$user"
    # mkdir "$home"
    # chown "$user:$group" "$home"