When a shell script is executed, the default directory would normally be the current directory of the user when the script is called. If you get into a situation wherein you want to determine the location of the shell script when it was called by the user, you can do the following within the shell script:
fullpath=`which $0`
scriptdir=`dirname ${fullpath}`
The scriptdir variable would contain the directory where the running script is stored. The which program returns the full path of the called script (e.g. /usr/bin/mybashscript.sh) while the dirname program returns the directory portion of the argument which was passed to dirname.
One use for it would be if for example you need to know where the shell script was stored because you need to call another script that was also stored in that directory when it was installed.
Author:
kihbord
Tags: dirname, script, shell, which
I wrote a bash shell script that deletes all the tables in a mysql database and I thought I’d just post it here in case anyone might find it useful. It accepts one required argument which is the database name and one optional argument which is the username with DROP/CREATE DATABASE privileges to dbname .
#!/bin/bash
if [[ ${1} == '' ]]
then
echo “”
echo ” `basename ${0}` {dbname} [{user}]”
echo “”
echo ” {dbname} – is the name of the mysql database to zap”
echo ” {user} – optional, user ‘root’ is used as default”
echo “”
exit 1;
else
read -p “Are you sure you want to empty ${1} [Y/N]? ” ans
if [[ ${ans} == "y" || ${ans} == "Y" ]]
then
user=${2:-”root”}
echo -n “Using mysql user ‘${user}’, ”
mysql -u ${user} -p -e “drop database ${1};create database ${1};” && echo “${1} emptied.”
exit 0;
else
echo “Aborted.”
exit 1;
fi
fi
Note: Oh and be careful in using the script ‘coz it will erase all the data in your database so make sure you have backups.
Author:
kihbord
Tags: Bash, database, empty, MySQL