0

Here is an example of what I am trying to do:

I have a folder (called 'dir') that contains the following:

dir
|_sub1.rar
|_sub2.rar
|_sub3.rar

I will cd ~/ to dir and want to run a command that will extract all .rar files and place the contents into a folder with the same name. sub1.rar should be extracted to sub1, sub2.rar should be extracted to sub2, and so on.

1 Answer 1

2
set -e
cd dir
for rar in ./*.rar
do
  [ -f "$rar" ] || continue
  dir=${rar%.rar}
  mkdir "$dir"
  (
     cd "./$dir"
     unrar x "../$rar"
  )
  # maybe rm "$rar"
done

Nothing clever here. Assumes you have an unrar command that takes an x option to do the eXtract. Just run a loop over the things matching ./*.rar, make sure it is a file, make a directory, then use a subshell to change directory and extract it.

3
  • I ran a test with this and it seemed to be working fine but only extracted the first file then it closed the terminal down. I used an example for the directory being 'dir' but in reality it changes. Do I need to change the $dir to the actual path? I tried that but didnt work. Mar 22, 2023 at 11:34
  • im also not sure if by calling the compressed "files" maybe was the wrong terminology, There is a parent folder (which changes) and then a long list of subdirectories that are all compressed with rar. It would be nice to take out the cd in the command as I will cd into the parent folder first then run a command from there. Mar 22, 2023 at 11:41
  • For things you want to do more than once, the best idea is to put this into a file (a "shell script"). For flexibility I agree that the "cd dir" shouldn't be in the script, but I was just trying to match what I understood to be your requirements. There are 2 things with "dir" in them. At the start there is the hard coded one, to match your requirement. Then there is a variable which is the part of the rar file without the ".rar" on the end. Does this make sense?
    – icarus
    Mar 22, 2023 at 17:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .