Auto-extracting archives

I have a directory structure with archived files, many of which are zipped or tarballed up. So if I want to search for a file, I can’t really be sure that the file I’m looking for isn’t in a compressed file. So I wrote some scripts to automatically run over a directory tree and automatically extract any compressed files that it finds there. There are a few extra features, such as if the file is larger than 10MB then it will prompt for whether to extract it or not. I have a few other features for handling errors to add in, but I’m happy to post this version up now.

extract-archives.sh

#!/bin/bash
err=$1
err=${err:-1}
search() {
	find -iname "*$1" -print0 | xargs -i -0 `dirname "$0"`/extract-file.sh "$1" "$2" "$err" "{}"
}
search ".tar.gz" "tar xf" 
search ".tgz" "tar xf" 
search ".zip" "unzip -q" 

extract-file.sh

#!/bin/bash
exec 0< /dev/tty
path="$4"
file_name=`basename "$path"`
dir_name=`dirname "$path"`
new_name=`basename "$path" "$1"`
new_path="$dir_name/$new_name"
[ -e "$new_path" ] && exit 0
echo $dir_name/$file_name
file_size=`stat -c %s "$path"`
#echo -n "File is $file_size bytes."
printf "File is %'d bytes." $file_size
check=`echo "$file_size < 10485760" | bc`
if [ "$check" = "1" ]; then answer="y"; fi
while [ "$answer" != "y" ]; do
	read -n 1 -s -p " Extract? " answer
	[ "$answer" = "n" ] && echo && echo && exit 0
done
echo
mkdir "$new_path"
pushd "$new_path" > /dev/null 2>&1
$2 "../$file_name"
if [ "$?" != "0" ]; then
	popd > /dev/null 2>&1
	rm -rf "$new_path"
	echo
	answer=""
	while [ "$answer" != "y" ]; do
  		read -n 1 -s -p "Do you want to ignore this file? " answer
		[ "$answer" = "n" ] && exit $3
	done
fi
popd > /dev/null 2>&1
echo

Leave a Reply