Reputation: 15
I have an old script where I extract the contents of archives into a new directory with the name of the archives. I need to simplify this as I find it inefficient since the commands run regardless. I'm not an expert with bash, and this worked for a while, but has become unbearable of late.
I get constant errors because the directory is already created or is not a unzip/unrar archive. I don't know how to check if the file is unrar or zip format prior to starting the script so I don't know how to put together a proper if/else for loop. I'm no expert with bash and this is just a small portion of a much larger script all written in bash years ago.
for x in $(find -name '*.cbr'); do dir=${x%%.cbr}; mkdir "$dir"; unzip -d "$dir" $x; done
for x in $(find -name '*.cbr'); do dir=${x%%.cbr}; mkdir "$dir"; unrar e $x "$dir"; done
for x in $(find -name '*.cbz'); do dir=${x%%.cbz}; mkdir "$dir"; unzip -d "$dir" $x; done
for x in $(find -name '*.cbz'); do dir=${x%%.cbz}; mkdir "$dir"; unrar e $x "$dir"; done
Upvotes: 0
Views: 494
Reputation: 15
Thanks for the feedback, I ended up doing something else.
for x in $(find -name '*.cbr' -o -name '*.cbz');
do dir=${x%.*};
mkdir "$dir";
unrar e $x "$dir" || unzip -d "$dir" $x;
done
Which is what I was looking to do, only attempt to create the directory once, and make a choice between unrar or unzip. Also, far more clean than what i previously had.
Upvotes: 0
Reputation: 7787
You could check the file types manually with file
or some smarter alternative, but my recommendation would be to just change your tool. atool
works with just about any archive format and unarchives into a directory formatted the way you're creating directories, by default (and creates a directory Unpack-[random number]
if there's already a file or directory by that name). Then you could just use one loop, remove the need to create a destination directory.
valid_exts=("zip", "rar") # etc
for f in $(find . -type f); do
if [[ "${valid_exts[*]}" == *"${f: -3}"* ]]; then
aunpack "$f"
fi
done
atool
is available in most package repositories.
If that won't work for you, I think it would be easier to use Python or some other language to do the tedious work: write out a dictionary of filetypes and unarchiving commands, then use a similar loop and call the commands from your higher-level script.
Upvotes: 1