notes/scripts/xpress
2022-09-04 04:47:50 -07:00

94 lines
2.9 KiB
Bash
Executable file

#!/bin/bash
# Error handling
set -e
# To be implemented:
# dependencies=("echo" "sed" "tar" "zip" "bzip2" "gzip" "gunzip" "pax" "7z" "ar" "cpio" "brotli" "lzip" "rzip" "xz" "zstd")
#Use for loop to check if recognized file formats have been passed to first argument
# For styling/colorizing output
txtbld=$(tput bold)
txtblue=${txtbld}$(tput setaf 4)
txtred=${txtbld}$(tput setaf 1)
txtgreen=${txtbld}$(tput setaf 2)
txtyellow=${txtbld}$(tput setaf 3)
txtwhite=${txtbld}$(tput setaf 7)
# Dependency check
function dependencycheck()
{
numdependencies="$#"
dependencies=("$@")
missingdependencies=0
for ((i = 0; i < numdependencies; i++)) ; do
if ! command -v "${dependencies[$i]}" &> /dev/null ; then
echo "${txtred}dependency not met: ${dependencies[$i]}${txtwhite}"
missingdependencies=$((missingdependencies+1))
fi
done
if [ $missingdependencies -gt 0 ] ; then
echo "${txtred}Please install needed dependencies${txtwhite}"
exit 1
fi
}
# Main Dependency check
dependencycheck echo sed
# Intro Prompt
echo "${txtgreen}xpress: a simple shell script for compressing common file formats"
# Reset output style
tput bold & tput setaf 7
# grabs the extension string
extension=$(echo "${1}" | sed 's/^[^\..:]*[\..*]//')
# grabs the filename/directoryname string
fdname=$(echo "${1}" | sed 's/\..*$//')
# create an array and a for loop of various
# ".txt" and ".js" and ".c" and ".py" files etc... for here
# if the file is a .txt file...
forbidden=".txt"
# if grep -q ".txt" <<< "${1}" ; then
if grep -q "${forbidden}" <<< "${1}" ; then
# if extension has "txt." in it, remove "txt." from extension
# this is mess, but put another if statement and another array that compares .txt to txt.
extension=$(echo "${extension}" | sed -r 's/^txt.//g')
# doesn't work:
# extension=$(echo "${extension}" | sed -r "s/^$forbidden//g")
# appends .txt to the filename if .txt exists in the original argument
# fdname="${fdname}.txt"
fdname="${fdname}${forbidden}"
fi
# Simply copy and paste, changing extension string and extraction method below
if [[ -d $fdname ]] ; then
if [ "${extension}" == "tar" ] ; then
dependencycheck tar
echo "${txtblue}compressing .tar...${txtyellow}"
# main compression method
tar cf "${1}" "${fdname}"
echo ".tar compression finished!${txtwhite}"
fi
if [ "${extension}" == "tgz" ] ; then
dependencycheck tar gzip
echo "${txtblue}compressing .tgz...${txtyellow}"
# main compression method
tar -czf "${1}" "${fdname}"
echo ".tgz compression finished!${txtwhite}"
fi
elif [[ -f $fdname ]] ; then
if [ "${extension}" == "gz" ] ; then
dependencycheck gzip
echo "${txtblue}compressing .gz...${txtyellow}"
# main compression method
gzip --keep "${fdname}"
echo ".gz compression finished!${txtwhite}"
fi
fi