/ Terminal

Unzipping all files in a directory using Bash

I have a ton of audiobook downloads in a folder, that I wanted to unzip and delete the old files. Doing this manually is boring and repetitive.

To solve this, the following script worked pretty well! I run this manually in the bash terminal.


# Modifying previous script at: https://www.santoshsrinivas.com/text-manipulation-on-the-command-line/

# Unzip all *.rar files in the temporary downloads directory

cd /Volumes/Seagate\ Slim/Books-Downloads

# Get only the filenames: https://unix.stackexchange.com/questions/136884/how-to-use-a-shell-command-to-only-show-the-first-column-and-last-column-in-a-te
# files=$(ls -l *.rar | awk '{print $9}')

# Moving to find. https://askubuntu.com/questions/217742/list-files-of-particular-extension
files=$(find . -name "*.rar")

# Credit: [shell - How to loop over the lines of a file? - Unix & Linux Stack Exchange](https://unix.stackexchange.com/questions/7011/how-to-loop-over-the-lines-of-a-file)
IFS=$'\n'       # make newlines the only separator
set -f          # disable globbing

for f in $files; do
  echo "File is: $f"

# Installations required:
# brew install unrar
# sudo apt-get install unrar

# Unzip files
for f in $files; do
  echo "Unzipping file: $f"
  # Create directory name: https://askubuntu.com/a/879323
  dir=$(echo $f | awk '{gsub(/.rar/,"")}1') #remove .rar from from the filename for directory
  mkdir -p "$dir"
  unrar e -r $f "$dir/"

# Delete old files after unzipping all. Out of caution
# UNCOMMENT and run explicitly after everything works!
# for f in $files; do
#   echo "Deleting file: $f"
#   rm $f
# done