Home » Articles » Shell Script function get password

Shell Script function get password

How to securely get a password from a user in a POSIX Compliant Shell Script.

 

There is 2 ways to create a function to securely get password in a shell script.

  • 1. ksh93 and bash compliant:
    read -rsp "contextual message" variable
  • 2. POSIX Compliant:
    printf %s "contextual message"; stty -echo; read passwd; stty echo; printf %s "$password"

 

1. Here is an example of function ksh93 and bash compliant

### Simple function to securely get a password from a user
f_get_password ()  #$1="Message to show to user before capturing password"
{
  # Print a meaningful message to the user
    ## We send our contextual message to stderr so it won't pollute our variable
    ## receiving the output of this function.
  printf "$1" >&2

  # Capture the password without displaying it on the screen
  read -rsp "$1" passwd

  # Return the password to the function caller
  printf %s "$passwd"

  # Return the prompt on its own line
  printf "\n" >&2
}

Example of usage:

 password=$(f_get_password "Enter your password") && echo "The password is: $password"

Output:

Enter your password

The password is: mypassword

 

2. Here is an example of function POSIX Compliant

### Simple function to securely get a password from a user
f_get_password ()  #$1="Message to show to user before capturing password"
{

  #Display a meaningful message to the user
    ## We send our contextual message to stderr so it won't pollute our variable
    ## receiving the output of this function.
  printf "$1" >&2

  # Disable echo.
  stty -echo
  # Set up trap to ensure echo is enabled before exiting if the script is terminated while echo is disabled.
  trap 'stty echo' EXIT

  # Capture the password without displaying it on the screen
  read passwd

  # Return the password to the function caller
  printf %s "$passwd"

  # Enable echo.
  stty echo
  trap - EXIT
  printf "\n" >&2
}

Example of usage:

 password=$(f_get_password "Enter your password") && echo "The password is: $password"

Output:

Enter your password

The password is: mypassword

Leave a Reply