Don't Script Your Password! Add Simple Prompts to Shell Scripts
I hate typing long shell commands, so I often create for myself short shell scripts that perform common tasks for me. I can hard-code all those options and arguments. Sometimes, though, there are a few bits that I want to change on a run or I don't want to hard code into a shell script.
Here's an excellent example: I don't want my password stored in a shell script. Ideally, what I want is to be prompted for my password.
There is a very simple shell built-in that you can use to do this: read
. Here's how it's used.
<!--break-->
Here's how it works. Say I have a fictional command called my-login -u USERNAME -p PASSWORD
. It takes two arguments: username and password. So I might build a shell script named do-my-login.sh
like this:
#!/bin/bash
USER=matt
PASS=supersecret
my-login -u $USER -p $PASS
That will certainly work, but I don't like having my password in the file. I'd rather be prompted for my password, but unfortunately my-login
doesn't provide this. So here's a minor tweak to add an interactive prompt to our script:
#!/bin/bash
USER=matt
read -p "Password for $USER: " PASS
my-login -u $USER -p $PASS
The important change is on the fifth line, where we use read
to prompt the user. Notice that the last argument (PASS
) is the name of the variable into which the response will be stored. The -p
option takes a string that it will use to prompt me:
$ ./do-my-login.sh
Password for matt: supersecret
But wait! I don't want my password echoed back to the console like that! To suppress the output, I can use the -s
prompt to silence the output:
#!/bin/bash
USER=matt
read -s -p "Password for $USER: " PASS
my-login -u $USER -p $PASS
Now when I respond to the "Password for matt" prompt, my password will not be echoed back to me.
I'm not guaranteeing that this is the most secure way to handle password prompts. (Between the prompt and the shell execution, the password is in cleartext.) But it performs exactly what I need for quick local shell scripts, and it's certainly more secure than hard coding passwords into scripts.