Oxaric’s Blog

A compendium of amazing things…

Posts Tagged ‘script’

Make A BASH Script Globally Executable

Posted by oxaric on December 4, 2008




Bash scripts are great! They make life a lot easier. But they can be a pain to drag around using mv and cp to get them to the right directory so you can execute them directly using: ~$ ./myscript.sh. Thankfully there is a much better way to run often used Bash scripts.


First, before we start you need to make sure the Bash script you’re interested in is executable. To be executable the script file needs the proper permission to run on your system. The command needed to give a file permission to run is chmod +x followed by the name of your script file.


This looks like:

~/test> chmod +x myscript.sh



Once your script is executable you need to copy it to a directory that your system expects to contain executable scripts and code. On most systems you will have a choice between two directories. If you are the only user of your system you can cpy your script to either /usr/bin or /usr/local/bin. If you share your system with other people it’s best to copy your script to /usr/local/bin. You will most likely need super-user privileges to copy your script to either of these directories so you’ll most likely need to use the sudo command or an equivalent. The sudo command will give you temporary super-user privileges and allow you to copy the script. Now you can directly copy the script into one of the stated directories but it is my preference to remove the .sh from my script file names before copying them.


Here are two script file copy examples:

~/test> sudo cp myscript.sh /usr/bin/myscript
~/test> sudo cp myscript.sh /usr/local/bin



Once you copy your script file it will be executable from any directory in your system. Simply type the name of your script file, hit enter, and your script will execute. Give it a try!

Posted in BASH, Linux, Tips | Tagged: , , , , , , , | Leave a Comment »

Quick BASH Script For Easier PHP Execution

Posted by oxaric on December 4, 2008




If you’re not running a web server, such as Apache, you might find PHP script can be a bit annoying to run. First you write your .php script, save the file, run the file through PHP, save the output into an .html file, and finally open the .html file in your preferred browser.


In order to simplify the steps needed to view the results of your .php script I created the Bash script below to automate some of the intermediary steps. The script takes the filename of a .php script, runs it through PHP, saves the resulting .html code as filename.html, and then opens the html file in Firefox.


Example:

~/test> ./runphp.sh myscript.php


Click to directly download runphp.sh


# Louis Casillas, oxaric@gmail.com
# Usage:
#       ~$ ./runphp.sh myphpfile.php


# Takes a php filename and executes the php code which
# creates html code.  Saves the resulting html code 
# into filename.html and opens the html file with
# Firefox.


# Assumes you have a version of php and firefox  
# installed on your system


if [[ "$1" == "" ]]; then
   echo
   echo "Specify a php filename"
   echo


   exit
fi


php_filename="$1"
php_filename_size=${#php_filename}
period_position=-1


# search for the last period in the passed filename
for ((i=$php_filename_size;i>=0;i+=-1)); do


   if [[ "${php_filename:$i:1}" == "." ]]; then
      period_position=$i
      break;
   fi
done


# if the passed filename contains a period then erase the
# file extension and add .html to the filename
if [ $period_position -eq -1 ]; then
   html_filename="$php_filename"".html"
else
   html_filename="${php_filename:0:$period_position}"".html"
fi


# run the php code and store the resulting html code
php $php_filename > $html_filename


# open the html file in firefox
firefox $html_filename

Posted in BASH, Linux, PHP | Tagged: , , , , , , , , , | Leave a Comment »

Linux BASH Aliases

Posted by oxaric on November 17, 2008

If you use bash then right now you can create aliases. An alias allows you to define a command that will call another command that is much longer or doesn’t automatically have the options you want.


If you want to list all of the files in your current directory you would use the command "ls". However, this command by itself will not show you hidden files. In Linux any file that starts with a period “.” is considered a hidden file. If you want to see all the files in your current directory including normal and hidden files you would need to use the command "ls -A".


Typing "ls -A" a few times isn’t such a big deal but if you are constantly using this command it would be quicker to create a bash alias. To create a bash alias we use the command “alias”. Makes sense huh? :)


Here is the basic format for the alias command:
alias new_command_name='old_command -plus_the_options_you_want'


NOTE: The new command name does not have any quotes around it but the old command with the added options has single quotes around it.


To make an alias for "ls -A" you need to type the following in your bash shell:

~/test> ls alias ls=’ls -A’ grep a.out



Once you’ve typed this line hit enter and the alias is created. Now during your current bash session if you want to see both the hidden and normal files in your current directory you only need to type "ls".


But wait!



If you create an alias manually like above you will lose all your aliases when you close the bash shell. If you want these aliases to be a permanent feature of your bash shell you need to do two things.

  1. Add the following line to your "~/.bashrc" file:
    if [ -f ~/my_bash_additions ]; then
       . ~/my_bash_additions
    fi



    NOTE: To edit this file you will need to be root or use "sudo".

  2. Create a file in ~/ called “my_bash_additions” and put your alias commands into this file.



Once you’ve done this all that’s left is to restart your bash shell. All of your aliases will be saved and ready for use. If you typed any commands wrong or anything is amiss you will probably get an error message when your bash shell is loading. If you get any errors go back into your “my_bash_additions” file, fix the errors, and re-start your bash shell. But I’m sure you’ll never make any mistakes so you’ll never have to do this. :)


Extra



Another cool thing you can do with your bash shell is to edit the way your command prompt looks. You can make your prompt colorful, plain, add extra information such as the current time, lots of stuff.


Here is a site with good information about editing your command prompt.


I’ve uploaded my own “my_bash_additions” file. Feel free to download it and try it out. It has a lot of features I like. It doesn’t have too many comments but it shouldn’t be too hard to understand.


Click to directly download my_bash_additions

Have fun playing!

Posted in BASH, Linux, Tips | Tagged: , , , , , , , | Leave a Comment »

Automated Harddrive Mounting Script

Posted by oxaric on November 15, 2008

I have 2 big 500 GB harddrives in USB cases with 3 partitions per drive. When they are connected to my machine the system automatically mounts them to /media and this seems great in theory. I only noticed something annoying after the drives laid idle for a while. My machine would quietly lose touch the drives and their files would no longer be accessible. However, the partition names would still remain in /media becoming ghost partition points.


If I accessed either drives after they had gone to sleep they would be mounted again but because the first mount points were still in /media my system seemed to like to randomly append an ‘_’ to the names of the mount points… sometimes… when it felt like it. The problem with this is that if anything running on my machine was looking for ‘/media/my_usb_drive’ it might find this mount point but because it is has become a ghost mount point the program will find nothing inside. The real drive would now be mounted to ‘/my_media/usb_drive_’.


So I created a script to deal with automatically finding the drives attached to my computer and mounting them to permanent mount points I created in /mnt. The mount points are simply directories I created in /mnt for the sole purpose of being a permanent home for my drive partitions. Now if the drives go to sleep I can simply run this script file and it will wake up the drives that are sleeping and mount them in their proper place in /mnt.


The benefit of this is that I no longer have to worry about having ghost mount points and I can use absolute file paths with no problems. Also, if I unplug and plug back in one of the drives I run this script and it automatically finds the correct /dev location of the drive and mounts it for me.


The script is fairly simple and contains enough comments that it should be fairly easy to edit it for your own needs. It is currently setup for my own system. Also, notice this program does not need to be used just with USB drives. Any drive type will work.


An extra tip


If you really hate to have your drives fall asleep you can directly edit your cron job process by using “crontab -e” and adding the line for each partition or drive:
“0 1 * * * ls /path_to_drive/my_mount_point”


The cron job process executes a command at a specific time like 1 AM for a system backup or at set time interval like every hour. Adding the above will tell the cron job to poke your drives every hour to keep them awake. Although if you don’t have a serious reason for using this you’ll save energy and have happier drives by letting them fall asleep. :) You could also setup cron to execute this script every so often just to make sure you’ll definitely keep your drives awake and mounted properly.


Click to directly download mount-usb-drives.sh

#!/bin/bash
# file name 'mount-usb-drives.sh'
# coded by: Louis Casillas, e-mail: oxaric@gmail.com

# Below are the physical IDs of the drives
# To see this run: $ sudo fdisk -l
# look at Disk identifier:

# ID: USB DRIVE: S_DRIVE
S_ID=0x44fdfe06

# ID: USB DRIVE: P_DRIVE
P_ID=0x9a4c35e6

# My USB drives are FAT32 so they use the vfat format to be mounted
MY_FILE_FORMAT="vfat"

# this is my user ID
# To see this run: $ id
MY_USER_ID=1000

total_max_drives_to_find=2 # number of USB drives I have
number_of_drives_found=0

echo
echo "Attempting to locate connected drives..."

# grabs a list of all the drives connected to the machine
sudo fdisk -l | column > /tmp/current_drives_connected.txt

# setup the input so the while loop will read every
# line from the file 'current_drives_connected.txt'
exec< "/tmp/current_drives_connected.txt"

# remove the temp file
rm /tmp/current_drives_connected.txt

while read line
do
    # takes the current line and looks for the physical ID
    # of the S_DRIVE
    test="$(echo "$line" | grep "$S_ID")"

    # if the ID was found then attempt to mount the drives
    if [[ "$test" != "" ]]; then

        number_of_drives_found=$(( $number_of_drives_found + 1 ))

        echo
        echo "S_DRIVE FOUND!"
        echo "Attempting to mount S_DRIVE..."

        # burn a line
        # the line after the one that contains the physical drive ID
        # has nothing we want
        read

        # read in the line that will tell us where linux has mounted
        # the drive. usually /dev/s__
        read line

        # grab the basic location i.e. /dev/sdb
        dev_location="$(echo $line | head -c8)"

        # my USB drives have 3 partitions and I have created a permanent location
        # for them in my /mnt drive.
        # this will attempt to mount the partitions. If they are already mounted
        # then mount will display this
        sudo mount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""1" /mnt/s-one
        sudo mount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""2" /mnt/s-two
        sudo mount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""3" /mnt/s-three
    fi

    # takes the current line and looks for the physical ID
    # of the P_DRIVE
    test="$(echo "$line" | grep "$P_ID")"

    # if the ID was found then attempt to mount the drives
    if [[ "$test" != "" ]]; then

        number_of_drives_found=$(( $number_of_drives_found + 1 ))

        echo
        echo "P_DRIVE FOUND!"
        echo "Attempting to mount P_DRIVE..."

        # burn a line
        # the line after the one that contains the physical drive ID
        # has nothing we want
        read

        # read in the line that will tell us where linux has mounted
        # the drive. usually /dev/s__
        read line

        # grab the basic location i.e. /dev/sdb
        dev_location="$(echo $line | head -c8)"

        # my USB drives have 3 partitions and I have created a permanent location
        # for them in my /mnt drive.
        # this will attempt to mount the partitions. If they are already mounted
        # then mount will display this
        sudo mount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""1" /mnt/p-one
        sudo mount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""2" /mnt/p-two
        sudomount -t "$MY_FILE_FORMAT" -o uid="$MY_USER_ID" "$dev_location""3" /mnt/p-three
    fi
       
    # if all the drives were found then exit the while loop
    if [ $number_of_drives_found -eq $total_max_drives_to_find ]; then
        break
    fi
done

echo

Posted in BASH, Linux, Programming | Tagged: , , , , , , , , , | Leave a Comment »

utar BASH script

Posted by oxaric on November 14, 2008

Imagine a tar file has the structure:
root area/directories/files


Typically there are no files in the root area. If there are this file is called a ‘tarbomb’. The problem with a tarbomb is that during extraction the files in the root area burst into your current directory and cause a mess. It can be tough to tell which files in your current directory were there before extraction and which are there courtesy of the tarbomb. This is a real pain and usually requires tedious removing or moving of each invidivual file.


Not fun!


Needless to say I’m not a big fan of tarbombs. I lost a good amount of sleep but I finally finished writing a script that robustly prevents any harm from tarbombs.


I’m happy now. :)





Here are some cool points of the script:

  • Completely protects against tarbombs! :D
  • It has 3 options which it can receive in any order before or after the tar file name and specific extract path.
  • Allows the specific extract path to come after the tar file name if the tar file name contains “.tar”
  • It has robust error messaging.
  • It has a nice help menu.
  • Has a lot of good comments and easy program structure for anyone looking to follow the code.



To demonstrate this script let’s look at the bad ‘tarbomb.tar’. Peering into it’s structure we can see this is an insidious tarbomb.

readme.txt <--- residing in the tar root space!
/super/readme.txt
/super/cool/man.txt



Normally if you try to extract this tar file the script will warn you the file is a tarbomb and exit. But for this example let’s force the extraction into the path “iam/” by using this code:

~/test> ./utar.sh tarbomb.tar iam/ --force

Warning! A tarbomb was detected!
Forcing the extraction...

Found a duplicate file: 'readme.txt': renaming it to 'readme.txt-1'


~/test>



What happens when this script is run is:

  • Determines tarbomb.tar is in fact a tarbomb but because of option “–force” it will continue the extraction.
  • Create the “iam/” directory if needed and extract all the files not in the root space into the “iam/” directory.
  • Lastly it will move the files in the root space into “iam/”



The folder structure will look like this:

../iam/readme.txt-1
../iam/readme.txt
../iam/cool/man.txt


You might notice the file originally in the tar root space now has a “-1″ appended to it’s file name. The issue here is that the tarbomb had a file in it’s root area and a file in it’s first directory with the same name. So when files in the root area are placed into the main directory a number has to be appended to it’s file name to ensure no files are overwritten.


I hope someone can get some use out of this script. I removed the “.sh” and put it into my /usr/bin directory so I definitely use it. The code should easily copy and paste but I’ve only tested it in Firefox.


Use it. Rip it up. Learn from it. Play with it. :)


I’d like to hear some feedback!

If you want to study the source code or use this script I suggest downloading it. Different browsers have a tendency to mess up the formatting of the code.



Click to directly download utar.sh

#!/bin/bash
# file name 'utar.sh'
# coded by: Louis Casillas, e-mail: oxaric@gmail.com
# version 1.1

# How to use:
# In a linux shell or cygwin:
# ~/directory-containing-this-script$ sudo chmod +x utar.sh
# ~/directory-containing-this-script$ ./utar.sh

# This script will protect against tarbombs and allow you
# to choose the path to extract the tar file into.
# To know more type: ./utar.sh

TRUE=0
FALSE=1
ERROR=2

OFF=0
ON=1

NO=0
YES=1

SUCCEEDED=0
FAILED=1

file_name=""
optional_extraction_path=""
help_option=$OFF
force_option=$OFF
keep_root_option=$OFF

num_of_dirs_passed=0
is_a_tar_bomb=$NO

# the initial temporary directory name
temp_dir="this-is-my-directory-to-untar-in"

function display_help_and_exit
{
   echo
   echo "Usage: utar [[FILE]] [EXTRACT_PATH/] [-k] [-f]"
   echo
   echo "utar extracts a tar file while preventing tarbombs to explode"
   echo "and allows the user to specify the tar extraction path"
   echo
   echo "     [EXTRACT_PATH/]            extract files in this path"
   echo "                                which replaces the original root directories"
   echo
   echo "     -k --keep-root-dir         appends the [EXTRACT_PATH/] to the start of"
   echo "                                the tar file's root directories"
   echo "                                implies [EXTRACT_PATH/] is given"
   echo
   echo "     -f --force                 force extraction"
   echo "                                needed to force the extraction of a tarbomb"
   echo
   echo "     -h --help                  display this help list"
   echo
   echo "Examples:"
   echo "     utar archive.tar           # extracts all files from archive.tar"
   echo "     utar archive.tar foo/      # extracts the files into directory foo"
   echo "     utar -f archive.tar        # forces an extraction even if"
   echo "                                # archive.tar is a tarbomb"
   echo

   exit $SUCCEEDED
}

# receives the exit code of the last system command called
# if the command had an error then display an error message
# and exit
function system_command_error_exit
{
    echo
    echo "utar: An error occurred while trying to use a system command."
    echo "utar: See the error message above."
    echo "utar: Exiting..."
    echo

    exit $FAILED
}

function did_the_system_command_work
{
   # $1 gives us the return result of the system command
   if [ $1 -ne $SUCCEEDED ]; then

      delete_the_temp_directory
      system_command_error_exit
   fi
}

function has_ending_forward_slash
{
   # grab the last character of the string and test if it is a forward slash
   if [[ "$(echo "$1" | tail --bytes=2 )" = "/" ]]; then
      return $TRUE
   else
      return $FALSE
   fi
}

function contains_a_forward_slash
{
   # test if the string has a forward slash
   # if true then this string is a directory
   if [[ "$(echo "$1" | grep "/" )" != "" ]]; then
      return $TRUE
   else
      return $FALSE
   fi
}

# determines if the string is a proper option
function is_an_option
{
   # must contain at least one hyphen at the beginning of the string 
   # to be considered an option
   if [[ $(echo "$1" | head --bytes=1 | grep "\-" ) = ""  ]]; then
      return $FALSE
   else
      return $TRUE
   fi
}

function evaluate_parameter
{
   if is_an_option "$1"; then
      # evaluate which option was used and set the necessary variables
      # if it is an improper option then exit
      case "$1" in

         "--help")
            help_option=$ON
         ;;
         "-h")
            help_option=$ON
         ;;
         "--force")
            force_option=$ON
         ;;
         "-f")
            force_option=$ON
         ;;

         "--keep-root-dir")
            keep_root_option=$ON
         ;;
         "-k")
            keep_root_option=$ON
         ;;
         *)
            echo "utar: invalid option: $1"
            echo "Try 'utar --help' for more information."
            echo

            exit $FAILED
         ;;
      esac # end of the case statement
   else
      num_of_dirs_passed=$(( $num_of_dirs_passed + 1 ))

      # determine if the passed parameter is a directory path
      # if it is then use it for the optional directory
      # however if it is a name and no file name is specified
      # then use this as the file name, otherwise it is
      # used as the optional directory
      if contains_a_forward_slash "$1"; then

         optional_extraction_path="$1"
         if ! has_ending_forward_slash "$1"; then
            optional_extraction_path+="/"
         fi
      else
         if [[ "$file_name" = "" ]]; then

            file_name="$1"
         else
            # test to see if one of the parameters has ".tar" in the name
            # if it does then switch the current file name with the
            # optional extraction path to allow the tar file parameter
            # to come after the extraction path
            if [[ $(echo "$1" | grep ".tar" ) = ""  ]]; then

               optional_extraction_path="$1""/"
            else
                  temp=$file_name
                  file_name="$1"
                  optional_extraction_path="$temp""/"
            fi
         fi
      fi

      # too many files or dirs passed
      if [ $num_of_dirs_passed -eq 3 ]; then
         echo "utar: an extra file or directory was passed: $1"
         echo "utar only extracts one tar to one directory at a time"
         echo "Try 'utar --help' for more information."
         echo

         exit $FAILED
      fi
   fi
}

# sorts out the 6 parameters passed and makes sure they are proper
function deal_with_the_parameters
{      
   if [[ "$1" != "" ]]; then
      evaluate_parameter "$1"
   else
      # exit if no parameters were passed
      echo "utar: You must specify a tar file"
      echo "Try 'utar --help' for more information."
      echo

      exit $FAILED
   fi

   if [[ "$2" != "" ]]; then
      evaluate_parameter "$2"
   fi

   if [[ "$3" != "" ]]; then
      evaluate_parameter "$3"
   fi

   if [[ "$4" != "" ]]; then
      evaluate_parameter "$4"
   fi

   if [[ "$5" != "" ]]; then
      evaluate_parameter "$5"
   fi

   # test if there are more options than is possible
   if [[ "$6" != "" ]]; then

      echo "utar: invalid command: $6"
      echo "Try 'utar --help' for more information."
      echo

      exit $FAILED
   fi

   if [ $help_option -eq $ON ]; then
      display_help_and_exit
   fi

###
# uncomment these lines if you want the extraction of a tarbomb
# to be automatically forced if an extraction path is specified
# except when the path is the current directory
#
#   if [[ "$optional_extraction_path" != "" ]]; then
#      if [[ "$optional_extraction_path" != "." ]]; then
#         if [[ "$optional_extraction_path" != "./" ]]; then
#            force_option="$ON"
#         fi
#      fi
#   fi
###
}

function create_the_temp_directory
{
   # if in some rare chance the temporary directory already exists
   # then append a random number to the end of the directory and 
   # test again.  
   # repeats until a non-existant directory is found.
   while [ -d "$temp_dir" ]
   do

      # grab a random number between 0 and 9
      temp_num=$(( $RANDOM % 10 ))

      temp_dir+="$temp_num"
   done

   temp_dir+="/"

   # make the temporary directory
   mkdir "$temp_dir"

   did_the_system_command_work $?
}

function delete_the_temp_directory
{
   # remove the temp directory
   rm -rf "$temp_dir"

   # $? gives us the return result of the system command
   if [ $? -ne $SUCCEEDED ]; then
      system_command_error_exit
   fi
}

function remove_dirs_from_the_temp_directory
{
   # grab a list of the files and directories in the temp directory
   temp="$(ls $temp_dir -A --file-type)"
   did_the_system_command_work $?

   # test if there any directories in the temp directory
   temp="$(echo "$temp" | grep /)"

   # if there are directories in the mpt directory then
   # delete them
   if [[ "$temp" != "" ]]; then

      # output list of dirs to file temp.txt
      echo "$temp" > "$temp_dir""temp.txt"
      did_the_system_command_work $?

      exec<"$temp_dir""temp.txt"

      # delete all  directories inside the temp directory
      # if any files are left in the temp directory this 
      # signifies the files would have normally been extracted 
      # into the current directory which means the tar file is a 'tarbomb'
      while read line
      do
         rm -rf "$temp_dir""$line"
         did_the_system_command_work $?
      done

      # this does not exactly need to be removed at this point because
      # later on the whole temp directory should be removed however
      # I left it in just in case there is some kind of error before
      # the temp directory is deleted.  Gotta hide the details! :)
      rm "$temp_dir""temp.txt"
      did_the_system_command_work $?
   fi
}

function test_for_being_a_tar_bomb
{
   create_the_temp_directory
   # extract the tar to temporary directory
   tar -xf "$file_name" -C "$temp_dir"
   did_the_system_command_work $?

   remove_dirs_from_the_temp_directory

   temp="$(ls $temp_dir)"
   did_the_system_command_work $?

   # test for any leftover files in the temp directory
   # if there are leftover files this tells us the tar
   # is a tarbomb
   if [[ "$temp" != "" ]]; then

      echo "Warning!  A tarbomb was detected!"

      is_a_tar_bomb=$YES

      # remove all leftover files in the temp directory
      rm -rf "$temp_dir"*
      did_the_system_command_work $?

      if [ $force_option -eq $ON ]; then
         echo "Forcing the extraction..."
         echo
      else
         delete_the_temp_directory
         echo "Exiting..."
         echo

         exit $FAILED
      fi
   fi
}

# check if the tar file exists
# if it does not exit
function check_for_tar_file
{
   if [ -f "$file_name" ]; then
      return
   else
      echo "utar: The specified file '$file_name' does not exist..."
      echo

      exit $FAILED
   fi
}

function create_specified_extract_path_if_needed
{
   # check to see if an optional extract path was given
   if [[ "$optional_extraction_path" != "" ]]; then

      # if the specified extract path does not exist then create it
      if [ ! -d "$optional_extraction_path" ]; then

         mkdir -p "$optional_extraction_path"
         did_the_system_command_work $?
      fi
   fi
}

function try_normal_extraction
{
   # test if no optional extract path was given
   # if none is given then perform a normal extraction
   if [[ "$optional_extraction_path" = "" ]]; then

      tar -xf "$file_name"
      did_the_system_command_work $?
   
      delete_the_temp_directory

      exit $SUCCEEDED
   fi
}

function try_maintaining_the_root_directory_extraction
{
   # if the -k or --keep-root-dir option was passed perform a normal
   # extraction into the specified directory
   if [ $keep_root_option -eq $ON ]; then

      tar -xf "$file_name" -C "$optional_extraction_path"
      did_the_system_command_work $?
      
      delete_the_temp_directory

      exit $SUCCEEDED
   fi
}

function extract_the_tar_bomb
{
   # extract the tar to the specified directory while
   # stripping the root directory
   tar -xf "$file_name" -C "$optional_extraction_path" --strip-components=1
   did_the_system_command_work $?

   # now take care of any files from a tarbomb
   # extract the tar to temporary directory
   tar -xf "$file_name" -C "$temp_dir"
   did_the_system_command_work $?

   # grab a list of the files and directories in the temp directory
   temp="$(ls $temp_dir -A --file-type)"
   did_the_system_command_work $?
  
   remove_dirs_from_the_temp_directory

   # output list of left over files to file temp.txt
   ls_results=$(ls "$temp_dir")
   did_the_system_command_work $?

   echo "$ls_results" > "$temp_dir""temp.txt"
   did_the_system_command_work $?

   exec<"$temp_dir""temp.txt"

   # go through the list of leftover files and
   # before moving them make sure they do not
   # have the same file name as any files in the
   # specified directory.  if they do then append
   # a hyphen and a number i.e. duplicate-file-1
   # increase the number until an untaken file name is found
   while read line
   do
      i=1

      # test to see if the file exists
      if [ -f "$optional_extraction_path""$line" ]; then

         while [ -f "$optional_extraction_path""$line""-""$i" ]
         do
            i=$(( $i + 1 ))
         done

         echo "Found a duplicate file: ""'$line':"" renaming it to ""'$line""-""$i'"

         # move the files back to the specified directory
         mv "$temp_dir""$line" "$optional_extraction_path""$line""-""$i"
         did_the_system_command_work $?
      else

         # move the files back to the specified directory
         mv "$temp_dir""$line" "$optional_extraction_path"
         did_the_system_command_work $?
      fi
   done

   delete_the_temp_directory

   exit $SUCCEEDED
}

function extract_to_the_specified_path
{
   tar -xf "$file_name" -C "$optional_extraction_path" --strip-components=1
   did_the_system_command_work $?

   delete_the_temp_directory

   exit $SUCCEEDED
}

### HERE STARTS THE CODE EXECUTION
deal_with_the_parameters "$1" "$2" "$3" "$4" "$5" "$6"

# makes sure the specified tar file exists
check_for_tar_file

# tests the tar for being a tarbomb
# creates a temporary directory
test_for_being_a_tar_bomb

# runs and exits if no specified extract path was given
try_normal_extraction

# if the extract path does not exist then create it
create_specified_extract_path_if_needed

# runs and exits if a specified extract path was given
# and the -k or --keep-root-dir option was passed
try_maintaining_the_root_directory_extraction

if [ $is_a_tar_bomb -eq $YES ]; then

   # runs and exits after extracting the tarbomb to the path given   
   extract_the_tar_bomb
else

   # runs and exits after extracting to the path given
   extract_to_the_specified_path
fi

Posted in BASH, Linux, Programming | Tagged: , , , , , , , , , | Leave a Comment »