Bash Script: Copying the contents of one directory to another

Shell Scripting @ Freshers.in

In this article, we’ll guide you through the process of creating a Bash script for this purpose, explain each part of the script, and provide a detailed example.

Prerequisites:

Before you begin, ensure you have the following:

  • A Unix-based system (Linux, macOS, or similar).
  • Basic knowledge of the Bash scripting language.
  • A terminal or shell for running the script.

The Bash Script:

Here’s a Bash script that takes a directory name as an argument and copies all its contents to a new directory:

#!/bin/bash

# Check if the user provided the source and destination directories.
if [ $# -ne 2 ]; then
  echo "Usage: $0 <source_directory> <destination_directory>"
  exit 1
fi
# Assign arguments to variables.
source_dir="$1"
destination_dir="$2"
# Check if the source directory exists.
if [ ! -d "$source_dir" ]; then
  echo "Source directory '$source_dir' does not exist."
  exit 1
fi
# Check if the destination directory exists; if not, create it.
if [ ! -d "$destination_dir" ]; then
  mkdir -p "$destination_dir"
  echo "Created destination directory: $destination_dir"
fi
# Copy the contents of the source directory to the destination directory.
cp -r "$source_dir"/* "$destination_dir"
echo "Contents of '$source_dir' copied to '$destination_dir'."

Script Explanation:

  1. Shebang (#!/bin/bash): The first line tells the system to use the Bash interpreter to execute the script.
  2. Argument Checking: The script checks if the user provided two arguments (source and destination directories). If not, it displays a usage message and exits.
  3. Variable Assignment: The script assigns the provided source and destination directories to variables for easy reference.
  4. Source Directory Check: It checks if the source directory exists. If not, it displays an error message and exits.
  5. Destination Directory Check and Creation: It checks if the destination directory exists. If not, it creates it using mkdir -p. The -p flag ensures that parent directories are created if they don’t exist.
  6. Copying Contents: It uses the cp command with the -r flag to recursively copy the contents of the source directory to the destination directory.
  7. Completion Message: Finally, it displays a message confirming that the contents have been copied.

Let’s assume you have a directory named source_dir with some files and subdirectories, and you want to copy its contents to a new directory named destination_dir. Here’s how you would use the script:

Replace copy_directory_contents.sh with the name you give to the script, and source_dir and destination_dir with your actual directory names.

Read more on Shell related articles

Author: user