/ Bash Scripts

Create and extract tar archives

This guide provides information on how to create a Bash script for creating and extracting tar archives.

Description

The script will enable users to:

  • Create tar archives
  • Extract tar archives
  • Provide custom options and settings

Pre-requisites

This guide assumes that you are familiar with Linux and Bash.

Steps

1. Creating the Bash Script

Open a text editor and create a new file named tar_script.sh.

nano tar_script.sh

2. Defining the Bash Interpreter

Start your script by defining the Bash interpreter:

#!/bin/bash

3. Defining Functions

We will define two main functions in our script: one for creating tar archives (create_tar), and another for extracting tar archives (extract_tar).

Creating Tar Archives

create_tar() {
    tar -cvf $1 $2
    echo "Tar file $1 created with contents: $2"
}

Here, $1 is the name of the tar file to be created, and $2 are the files to be added to the tar archive. -c creates a new archive, -v shows the progress in the terminal, and -f allows to specify the name of the archive.

Extracting Tar Archives

extract_tar() {
    tar -xvf $1 -C $2
    echo "Tar file $1 extracted to directory: $2"
}

Here, $1 is the name of the tar file to be extracted, and $2 is the directory where the files will be extracted. -x extracts the archive, -v shows the progress in the terminal, -f allows to specify the name of the archive, and -C specifies the directory for the extracted files.

4. Implementing User Input

The user can select whether to create or extract a tar archive, and specify custom settings.

read -p "Enter (c)reate or (e)xtract: " operation
case $operation in
    c)
        read -p "Enter name of tar file: " tarfile
        read -p "Enter files to archive: " files
        create_tar $tarfile $files
        ;;
    e)
        read -p "Enter name of tar file: " tarfile
        read -p "Enter directory for extracted files: " directory
        extract_tar $tarfile $directory
        ;;
    *)
        echo "Invalid option. Please enter 'c' for create or 'e' for extract."
        ;;
esac

Here, we are using the read command to get the user’s input, and case command to handle the user’s choice. If the user enters c, the create_tar function is executed. If e is entered, the extract_tar function is executed.

5. Save and Exit

Save the changes and exit from the editor.

6. Make the Script Executable

Make the script executable using the following command:

chmod +x tar_script.sh

7. Run the Script

Now, you can run the script with:

./tar_script.sh

Conclusion

This script provides the basic functionality for creating and extracting tar archives with the ability for user-provided custom options. Note that this is a basic implementation and might need to be modified according to different user needs and system environments.

Was this helpful?

Thanks for your feedback!