Remove hundreds of block users from drupal site using drush

There was a drupal site that I had to deal with recently. It had about 400 block accounts (the site had allowed user to register with administrator approval) - all of whom were junk accounts that needed removal.

 

There are modules that can be installed that will do this - but I did not want to install any modules on this production site. So I wanted to do this using a command line - linux based server with bash - using drush

 

The one line bash command is:

 
IFS=$'\n';users=($(drush @site sqlq  --db-prefix "select name from {users} where uid > 1 and status = 0;" |grep -v '^name$')); for user in "${users[@]}"; do drush @site --yes ucan "$user"; done
 

Notes:

 
  • There is no drush command that gives us the list of users - so I did an sql query for the name of the block users - i.e. user with status = 0 - select name from {users} where uid > 1 and status = 0 - the uid is needed so that we do not include anomyous - which is blocked.
  • The first line - which is the fieldname - name - is removed by using grep -v '^name$'
  • The result is put into a bash array with the resulted seperated by new line(IFS=$'\n').
  • This is then loop in a for loop running drush to delete each user