Skip to content

Instantly share code, notes, and snippets.

@ygol
Created June 23, 2017 12:22
Show Gist options
  • Save ygol/1014ffbd21b1ad2dd1cf9b1766d13808 to your computer and use it in GitHub Desktop.
Save ygol/1014ffbd21b1ad2dd1cf9b1766d13808 to your computer and use it in GitHub Desktop.
Drop databases selectively by matching any part of the name. (https://github.com/Kraymer/ezdropdb)
#!/bin/bash
# Copyright (c) 2017 Fabrice Laporte - kray.me
# The MIT License http://www.opensource.org/licenses/mit-license.php
# ezdropdb
# Removes PostgreSQL databases selectively by matching any part of the name.
readonly PROGNAME=$(basename $0)
usage() {
cat << EOF
USAGE: $PROGNAME [-s signal_name] pattern
$PROGNAME lists all databases that match the criteria given on the command line, prefixed by
an identifier.
It then prompts you for which databases to drop by entering corresponding identifiers.
OPTIONS:
see 'dropdb' USAGE
EOF
}
# Print array elements, one per line, prefixed by a letter identifier from a to z.
# Alternate lines background colours for best readability.
#
# $@ - array to print
print_alternate()
{
ps_grep_lines=("$@")
if [ ${#ps_grep_lines[@]} -eq 0 ]; then
echo "No databases found."
exit 0
fi
CTRL_REVERSE="\e[7m"
CTRL_RESET="\e[27m"
LINE_IDX=a
for ((i = 0; i < ${#ps_grep_lines[@]}; ++i)); do
cmd=`echo ${ps_grep_lines[$i]} | cut -f 2-99 -d " " | cut -c 1-128`
((i % 2 == 0)) && printf "${LINE_IDX}"
((i % 2 != 0)) && printf "${CTRL_REVERSE}${LINE_IDX}${CTRL_RESET}"
echo " ${cmd}"
LINE_IDX=$(echo "$LINE_IDX" | tr "0-9a-z" "1-9a-z_") # alpha increment
if [ $i -eq 25 ]; then
echo '...'
break
fi
done
}
ezdropdb() {
options=${@:1:$#-1} # all args but last
while IFS= read -r line; do
if [ ! -z "$line" -a "$line" != " " ]; then
databases+=("$line")
fi
done < <( psql $options -tl|cut -d'|' -f 1|sed -e '/^ *$/d'|grep -e "${@: -1}" | grep -v "$0" )
print_alternate "${databases[@]}"
echo " "
read -p "Drop databases: " cmd_ids
for (( i=0; i<${#cmd_ids}; i++ )); do
ascii_cmd_id=`printf "${cmd_ids:$i:1}" | od -A n -t d1`
idx=`expr $ascii_cmd_id - 97`
dbname=`echo ${ps_grep_lines[$idx]}`
dropdb $options $dbname
done
}
main() {
ezdropdb $@
}
main $@
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment