Find/Unrar/Delete Script

bashcommand linerarscript

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):

for rarfile in *.rar; do
    unrar x "$rarfile"
done

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

 cd ~
 mkdir .bin 
 echo 'PATH=$PATH:$HOME/.bin' >> .profile
 echo 'export PATH' >> .profile
 . ./.profile
 nano .bin/extract_all_rars

This gives you a simple editor for text files, essential commands are displayed at the bottom. Type

 #!/bin/bash

followed by the code block at the top, save the file and exit. Then (in the shell again) type

 chmod +x .bin/extract_all_rars

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, adding

 rm -f "$rarfile" ${rarfile%%.rar}.r{0..9}{0..9} 

after 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 (run echo 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 simple

rm -${rarfile%%.rar}.r??

does the trick as well.


If you don't have rar/unrar already:

  • Download RAROSX 4.2 from rarlab.com
  • In Finder, open ~/Downloads and double click the downloaded file to unpack. A rar folder will be created
  • Open Terminal and run the following commands

    cd ~/Downloads/rar
    sudo install -d rar unrar /usr/local/bin
    

    to install the binaries (executables)

  • We must also make sure that the shell afterwards finds the binaries

    cd ~
    echo 'PATH=$PATH:/usr/local/bin' >> .profile
    echo 'export PATH' >> .profile
    . ./.profile