Hi Everyone, this is my first bash script ever. I would really appreciate it if you could provide me with some comments and insights regarding correct function use, logic implementation, and a lead to how to implement the recursive functionality described in the script's body. Thanks a lot!
#!/bin/bash
#
# The following is a script designed to unpack 4 different compression types.
#
# Known compression type files are unpacked, otherwise, the script ignores them.
#
# The script accepts a file or a list of files, 2 flags which are -v (for verbose) and -r ( for recursive but currently not functional).
#
# The execution syntax is: unpack [-v] [-r] file [file...]
#
# !!!!! Didn't come up with a way to isolate the functionality of -r without code duplication.!!!!!!!!!!!!!!!!
decomp_files=0 # Counts decompressed files.
failed_decomp=0 # Counts filed decompression attempts.
is_verbose=false # States if -v was used (true if used).
is_unpackable=false # States if the can be decompressed.
# The function is responsible for detecting if the parameter provided to the script is a file or not.
# If it's a file, it isolates the type of compression and checks if the -v option is set.
function detect_file_type() {
for file in $@
do
if [ -f "$file" ]
then
# print & isolate compression type
comp_type=`file $file | awk '{print $2}'`
decompress $file $comp_type
if ( $is_verbose && ! $is_unpackable)
then
printf "Ignoring ${file}\n"
elif ( $is_verbose && $is_unpackable )
then
printf "Unpacking ${file}\n"
fi
fi
done
#TOOO: Add logical functionality to: "if file is directory -> cd inside -> repeat".
printf "Decompressed $decomp_files archive(s)\n"
}
# The function decompresses the file with the right binary after its identification.
# Invoked by the detect_file_type function.
function decompress () {
case $comp_type in
"gzip")
gzip --decompress $file
((decomp_files++))
is_unpackable=true
;;
"bzip2")
bunzip2 --decompress $file
((decomp_files++))
is_unpackable=true
;;
"Zip")
unzip $file
((decomp_files++))
is_unpackable=true
;;
"compress'd")
uncompress $file
((decomp_files++))
is_unpackable=true
;;
*)
((failed_decomp++))
is_unpackable=false
;;
esac
}
# This is the first function to be executed.
# The function checks for the optional flags and assigns the corresponding variables accordingly.
function main () {
# Check if the script was executed with parameters.
if [[ -z "${@}" ]]
then
printf "Command structure: unpack [-r] [-v] file [file...]\n"
exit 1
fi
if [ "$1" = "-v" ] || [ "$2" = "-v" ]
then
is_verbose=true
fi
if [ "$1" = "-r" ] || [ "$2" = "-r" ]
then
is_recursive=true
fi
detect_file_type $@
}
main $@
#!) only works if it's the first two characters in the file. \$\endgroup\$