Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Possible Duplicate:
How to hide commands typed in a Linux shell?
Reading passwords without showing on screen in Bash Scripts

I would like to take a password as input, but I want user to be able to enter it just like other utilities handle it i.e. the characters doesn't appear on the screen. I tried searching regarding this, but found no exact answer.

I need to take in a variable, and then I would match the input with a pre-defined standalone password hard-coded variable sourced from one of the config files at the beginning of the script.

Expected behaviour

$./startScript
username: mtk
password: ********

* shown as placeholders. I need this part to be invisible. Currently the password is displayed as the user types it.

How to do this?

share|improve this question
add comment

marked as duplicate by jasonwryan, Michael Mrozek Dec 9 '12 at 20:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers

If you use sh (or bash), you use read with option -s (secure).

read -s pass

will read password from user, not showing it to the output and store it to variable pass.

share|improve this answer
add comment

UNIX has 'getpass' C function to display a prompt and read the password with disabled echo.

The function gets the prompt string and returns a pointer to NULL-terminated string containing password. Don't forget about maximum passwords length (take a look at limits.h on your system for PASS_MAX or so).

Also pay attention that 'getpass' puts the password into internal static buffer, which is erased each time you invoke it. So, decent process should zero the buffer as soon as possible.

Here is a small program, showing the behavior:

#include <stdio.h>
#include <unistd.h>

int
main( int argc, char** argv ) {
    char* password = getpass( "Password: " );
    printf( "Your password is: '%s'\n", password );

    return 0;
}
share|improve this answer
add comment

I think this code should do what you want:

#!/bin/bash

unset username
unset password
echo -n "username:"
read username
prompt="password:"
while IFS= read -p "$prompt" -r -s -n 1 char
do
    if [[ $char == $'\0' ]]
    then
         break
    fi
    prompt='*'
    password+="$char"
done
share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.