Last active
April 6, 2021 11:34
-
-
Save roosto/2b0677316b2dc34f1704cb42b4c68b1f to your computer and use it in GitHub Desktop.
a secure bash shell function to interactively set and export an environment variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
function set-secret { | |
# TODO: handle signals: an ill-timed signal could leave the user | |
# with a non-sane terminal, which can really foul things up | |
# even for experienced users | |
ME='set-secret' | |
# state machine vars | |
do_help=false | |
export_to_env=false | |
return_status=0 | |
parsed_opt_count=0 | |
while getopts 'he' option | |
do | |
parsed_opt_count=$(( $parsed_opt_count + 1 )) | |
case "$option" in | |
h) | |
do_help=true | |
;; | |
e) | |
export_to_env=true | |
;; | |
*) | |
echo "$ME: error $option: unknown option" 1>&2 | |
return_status=1 | |
;; | |
esac | |
done | |
shift $parsed_opt_count | |
if [[ $return_status != 1 ]] | |
then | |
if [[ $# != 1 ]] | |
then | |
echo "$ME: error this command expects a single argument" 1>&2 | |
return_status=1 | |
elif echo "$1" | grep -q -i -e '^-*help$' | |
then | |
do_help=true | |
elif echo "$1" | grep -q -e '^[^a-zA-Z_]' -e '[^a-zA-Z_0-9]' | |
then | |
echo "$ME: error \`$1' is not a legal variable name;" 1>&2 | |
echo "Names must match /^[a-zA-Z_][a-zA-Z_0-9]*$/" 1>&2 | |
return_status=1 | |
fi | |
fi | |
if $do_help || [[ $return_status != 0 ]] | |
then | |
echo "Usage: $ME VAR_NAME" | |
echo '' | |
echo "Shell function to set VAR_NAME while concealing its value" | |
echo "tty echoing is set to off during value capture, so you can safely set secrets" | |
return $return_status | |
fi | |
var_name="$1" | |
stty -echo | |
read -p "enter value for \`$var_name': " "$var_name" | |
stty echo | |
if $export_to_env | |
then | |
export "$var_name" | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment