0
\$\begingroup\$

Please review my Bash code to create an authenticated, all privileged MySQL user plus a DB with the same name, through the MySQL CLI:

read -sp "DB user password:" dbrootp_1       && echo
read -sp "DB user password again:" dbrootp_2 && echo
read -sp "DB user password:" dbuserp_1       && echo
read -sp "DB user password again:" dbuserp_2 && echo

if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched" && exit 1 fi
if [ "$dbuserp_1" != "$dbuserp_2" ]; then echo "Values unmatched" && exit 1 fi

cat <<-DBSTACK | mysql -u root -p"$dbrootp"
    CREATE USER "$domain"@"localhost" IDENTIFIED BY "$dbuserp";
    CREATE DATABASE "$domain";
    GRANT ALL PRIVILEGES ON "$domain".* TO "$domain"@"localhost";
DBSTACK
\$\endgroup\$
0

1 Answer 1

3
\$\begingroup\$

Just executing the code, I'd receive 4 different inputs like this:

DB user password:
DB user password again:
DB user password:
DB user password again:

which would make me think that some thing went wrong in the first time, and I'd input the same password again. You are not making it obvious for the user to input root password first.

echo "Enter root user credentials"
read -sp "root user password:" dbrootp_1       && echo
read -sp "root user password again:" dbrootp_2 && echo
echo "Enter new user credentials"
read -sp "new user password:" dbuserp_1       && echo
read -sp "new user password again:" dbuserp_2 && echo

makes it slightly better.

if [ "$dbrootp_1" != "$dbrootp_2" ]; then echo "Values unmatched" && exit 1 fi
if [ "$dbuserp_1" != "$dbuserp_2" ]; then echo "Values unmatched" && exit 1 fi

You may wish to convey exactly which set of password was mismatched. It is more a UX debate though. You might not want to do that as it might cause some security vulnerability! However, look at

function error_quit() {
    local EXITCODE=$1
    local MESSAGE="$2"
    >&2 echo $MESSAGE
    exit $EXITCODE
}

[[ "$dbrootp_1" != "$dbrootp_2" ]] && { error_quit 1 "Values unmatched" }
[[ "$dbuserp_1" != "$dbuserp_2" ]] && { error_quit 1 "Values unmatched" }

Splitting into a function gives you an added benefit so that in future you might expand the script, and use the same minimal exit setup instead of copying it everywhere.

The >&2 directs the error to stderr stream.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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