Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Gabotronix's avatar

Bash script issue: can create User but password is not being set correctly

in my ubuntu 22.04 server I created a bash script that setups my server to serve laravel apps, one of the steps I do is:

  • Downloading mysql
  • Creating a non-root user,
  • Grant all privileges to non-root user.

I use this code inside my bash script:

#!/bin/bash

echo 'Downloading mysql, creating non-root database user with all grants and securing mysql'
sleep 3
sudo apt install mysql-server

# Prompt for database username
read -rp "Enter the database's owner username: " DB_USER

# Prompt for database password (first entry)
while true; do
    read -rsp "Enter the database password: " DB_PASSWORD1
    echo
    read -rsp "Re-enter the database password: " DB_PASSWORD2
    echo

    if [ "$DB_PASSWORD1" = "$DB_PASSWORD2" ]; then
        break
    else
        echo "Passwords did not match. Please try again."
    fi
done



# Connect to MySQL
sudo mysql <<EOF
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '$DB_PASSWORD';
CREATE USER '$DB_USER'@'localhost' IDENTIFIED WITH mysql_native_password BY '$DB_PASSWORD';
GRANT ALL PRIVILEGES ON *.* TO '$DB_USER'@'localhost';
FLUSH PRIVILEGES;
EOF



# Run mysql_secure_installation
sudo mysql_secure_installation
sudo service mysql restart

THE ISSUE:

Now , after everything is done, I try to log in mysql like this:

mysql -u user-p 

Where I enter EXACTLY the same user and password I was prompted to

I get the following error:

ERROR 1045 (28000): Access denied for user 'Faber'@'localhost' (using password: YES)

Now if I execute this command, where User and Password are EXACTLY the same I entered earlier

sudo mysql
ALTER USER 'DBuser'@'localhost' IDENTIFIED BY '161fd43c260030@&DB';
FLUSH PRIVILEGES;

I can correctly log in mysql, why can't I correctly setup the password via bash script, since I'm automating tasks with my bash script I'd like to avoid having to do the ALTER command...

0 likes
1 reply

Please or to participate in this conversation.