I'm a PC convert, and quite novice when it comes to shell/bash scripting, but I really want to learn/understand more.
My need: I need to be able to scan a folder, find any .rar files, extract the files in place, and delete the associated .rar afterwards. Each may also have the .r00, .r01, … files associated, so those need to be deleted afterwards as well.
Can someone help me figure out (and understand) how to write a script for this? The more comments, the better.
Best Answer
I assume you only want to scan the current folder (and not all other folders beneath it):
Key thing is to put the file name into "" when passing it to
unrar
to avoid any problems with spaces in the name.Now if you want to have this as a script you can run, you can do the following
This gives you a simple editor for text files, essential commands are displayed at the bottom. Type
followed by the code block at the top, save the file and exit. Then (in the shell again) type
to mark it executable (so the shell recognizes it as a command).
Automatic deletion has one caveat:
unrar
doesn't return an error status if things go wrong so you may loose your rar files. If this is not an issue, addingafter the
unrar
in the loop above will do the job. The second parameter is used to create all possible.r04
suffixes by first stripping away the suffix (${rarfile%%.rar}
) and then iterating from 0 to 9 twice to get all possible combinations (runecho foo{0..9}
in bash to see how it works). As most of these file names do not exist, I've added-f
as an option to avoid error messages.If you are fairly sure that no other files with a
.rXX
suffix are in the same directory, a simpledoes the trick as well.
If you don't have
rar
/unrar
already:~/Downloads
and double click the downloaded file to unpack. Arar
folder will be createdOpen Terminal and run the following commands
to install the binaries (executables)
We must also make sure that the shell afterwards finds the binaries