Bash - Check if an user existed in Django db

When deploying my Django app  to a server, I want to create a script to create Django superuser. The script will check if the inputed user_name existed, if YES, It will prompt me to change password, if NO, it will create the user for me.

I use the mysql command to query the user (auth_user table) from the shell just like the way I did in the previous blog spot (http://iambusychangingtheworld.blogspot.com/2013/06/bash-check-if-mysql-database-is-existed.html).

create_superuser.sh:

#! /bin/bash
# $1: db username
# $2: db password
# $3: db name
# $4: admin username
cd /home/projects/myproject/
. /home/.venv/myvenv/bin/activate
RESULT=`mysql -u $1 -p"$2" --skip-column-names -e "USE '$3';SELECT username FROM auth_user WHERE username='$4'"`
if echo "$RESULT" | egrep -q "$4" ; then
echo "$4 existed"
exec python manage.py changepassword $4
else
echo "$4 not existed" 
exec python manage.py createsuperuser --username $4
fi


Then, run the command:
# sh create_superuser.sh root root my_db admin

Notes:
The '.' in '. /home/.venv/myvenv/bin/activate' is 'source'  when you run directly in shell, because the real shell does not have 'source'

Comments