Bash magic oneliners

Getting the absolute path for current directory in script

This thing is helpful if you want to decouple your script login from pwd (the actual directory you have runned the script from):

DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )  

What it is doing:

  1. Get the relative path of the script's directory (the directory where bash script is located on file system) using dirname
  2. Change the directory to the relative directory
  3. Get the absolute path for the directory using pwd
  4. Store the absolute path in the DIR variable

You can read the DIR variable in your script using $DIR or ${DIR} syntax.

Using TAR with the absolute base path

If you want to use the absolute path with the tar command, you run it with the uppercase C flag:

tar -C $DIR -zcvf $target_file