Shell Scripting Help (extensions, string and more)

I am trying to set up some scripts to easily update the website's database and/or website files and am running into some issues.

The backup files to restore from .bz2 files (.sql.bz2 and .tar.bz2).

What I am doing is setting up the script to allow the user to specify WHICH backup file to restore from and to run the necessary steps but I am having problems with handling the address of the files because while I receive it as $1, once it is unzipped (bunzip2) the name has changed (the .bz2 is removed) and I have to update the reference to the new file.

Code:
#!/bin/sh

DB=$1    #this is the location of the backup file (example "/usr/home/util/backup/postgres.sql.bz2")

# determine if file is zipped (bz2) or not

file_ext=$(echo $DB | awk -F . '{if (NF>1) {print $NF}}')
if [ $file_ext == "bz2" ] ; then
  (
  bunzip2 $DB
  #HELP: how do I capture $DB without the .bz2 extension?
  #I need the example to become "/usr/home/util/backup/postgres.sql"
  )
fi
I have been trying with awk but I can't seem to get it to work while passing a variable, only when a string value is coded in and I want it to be dynamic.

Code:
awk 'BEGIN {
  str=$1
  sub(/sql.bz2/, "sql", str)
}'
Usually it either hangs, or comes back with not "unexpected (" or "awk not found" or some other error.

If there is an easier way to remove the trailing ".bz2" that would be great!

I am just starting my shell scripting learning and am not sure if the issues are what I am typing, or I am referencing a Linux command and it is different in FreeBSD, or what so any help is appreciated!

Thanks!
 
Ok, it took me a moment to get basename to work (didn't realize it uses ` instead of ' ).

Thank you! This looks like it will work as it brings back the entire directory address and the filename without ".bz2":
Code:
new_filename=`dirname $1`/`basename -s '.bz2' $1`

Thanks!
 
What wblock@ is referring to is this:

Code:
% DB=/usr/home/util/backup/postgres.sql.bz2
% echo ${DB%.bz2} 
/usr/home/util/backup/postgres.sql

The percent sign % deletes the shortest match of the pattern (.bz2 in this example) from the end of the variable given on the left side of the % sign.
 
Maybe you could turn the problem around, tacking on .ext when needed:

Code:
DB=foo.sql

[ -f "$DB.bz2" ] && bunzip2 -- "$DB.bz2"

shells case might fit the bill sometimes.

Code:
case "$DB" in
*.sql) ;;
*.tar) ;;
*.bz2) bunzip2 ... ;;
*.*) echo "$0: $DB has unsupported extension" >&2 ; exit 2 ;;
"") ...usage... ;;
*) ... ;;
esac

Juha
 
Top