Showing posts with label bash. Show all posts
Showing posts with label bash. Show all posts

Sunday, October 09, 2011

Making a bash script know its current directory location

I use the following variables at the beginning of my Bash script to get such information:

EXECUTED_FROM_DIR=`pwd`
THIS_SCRIPT_DIR=$(cd $(dirname "$0"); pwd)
cd $THIS_SCRIPT_DIR


#Do different tasks here
...


cd $EXECUTED_FROM_DIR

Bash Tips

To check if a file exists (The exclamation ! means "not") :
if [ ! -f ${TOMCAT_DIR}/conf/jobsapp.conf ]
then
  echo "Do something"
fi


To check if a script should be run by a specific user:
if [ "$(id -u -n)" != "root" ]; then
   echo "This script must be run as root user" 1>&2
   exit 1
fi

To prompt a user for an action:

read -p "Deploy on Tomcat (y/n)?" CONT
if [ "$CONT" == "y" ]; then
  echo "Deploying on tomcat...";
  echo "Finished deploying on tomcat.";
else
  echo "Copied files, but didn't deploy on tomcat.";
fi