Friday, June 7, 2013

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 (

#! /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 changepassword $4
echo "$4 not existed" 
exec python createsuperuser --username $4

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

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