shell script to tar multiple files & directories

Shell Script to Tar Multiple Files & Directories

Many times you may need to compress/archive multiple files & folders in your system. If you need to tar multiple files & directories it is advisable to use a shell script for it. In this article, we will look at how to create shell script to tar multiple files & directories in Linux.


Shell Script to Tar Multiple Files & Directories

Here are the steps to tar multiple files & directories in Linux.


1. Create empty shell script

Open terminal and run the following command to create an empty shell script in Linux.

$ sudo vi tar_multiple.sh


2. Add shell script to tar files & directories

Add the following lines to your shell script file.

#!/bin/bash

for f in "$@"
do
  sudo tar "$f".tar "$f"
done

In the above case, our shell script will take multiple files & directories and create separate tar files for each file/directory. $@ stores the list of command line arguments. For example, if you pass file1, file2, file3 in your command line argument, our script will create file1.tar, file2.tar and file3.tar respectively. It basically loops through the command line arguments and generates tar file for each iteration.

If you want to tar all files & directories together in a single file, then add the following code instead.

#!/bin/bash

files=""

for f in "$@"
do
  files+="$f "
done

sudo tar files.tar $files

In the above code, we first create an empty string variable $file. $@ stores the list of command line arguments. In our for loop, we append each file name to $files. Finally, we use a tar command to tar all those files into a single files.tar file.

Save and close the file.


3. Make shell script executable

Run the following command to make our shell script executable

$ sudo chmod +x tar_multiple.sh


4. Test Shell Script

Test shell script with different files & directories as shown below

$ sudo ./tar_multiple.sh file1.txt /home/data file3.txt

That’s it. In this article, we have seen two different ways to tar multiple files & directories into a single file.

Also read:

How to Check If Directory Exists in Shell Script
How to Create Wildcard Subdomain in Apache Server
How to Fix NGINX Upstream Closed Prematurely Error
How to Block Referrer Spam in Apache .htaccess
Shell Script to Delete Files in Directory

Leave a Reply

Your email address will not be published.