How to Copy a File in Bash

In Bash, the command used to copy files is cp. This command allows you to create a duplicate of a file or directory in a specified location. Below, we will explore the syntax of the cp command, along with examples and options.

Basic Syntax of the cp Command

The basic syntax for the cp command is as follows:

cp [options] source destination

In this syntax:

  • source is the path to the file you want to copy.
  • destination is the path where you want to copy the file to.
  • [options] are optional flags that modify the behavior of the command.

Example of Copying a File

Here’s a simple example of using the cp command to copy a file:

cp file1.txt file2.txt

In this example:

  • The command copies file1.txt to a new file named file2.txt in the same directory.
  • If file2.txt already exists, it will be overwritten without any warning.

Copying a File to a Different Directory

You can also copy a file to a different directory by specifying the destination path:

cp file1.txt /path/to/destination/

In this example:

  • The command copies file1.txt to the specified directory.
  • The new file will retain the same name as the original file.

Using Options with the cp Command

The cp command supports various options to customize its behavior. Here are some commonly used options:

1. -i Option

The -i option prompts you for confirmation before overwriting an existing file:

cp -i file1.txt file2.txt

In this example:

  • If file2.txt already exists, the command will ask for confirmation before overwriting it.

2. -r Option

The -r option is used to copy directories recursively:

cp -r dir1/ dir2/

In this example:

  • The command copies the entire directory dir1 and its contents to dir2.
  • If dir2 does not exist, it will be created.

3. -u Option

The -u option copies the file only if the source file is newer than the destination file or if the destination file does not exist:

cp -u file1.txt file2.txt

In this example:

  • The command will only copy file1.txt to file2.txt if file1.txt is newer or if file2.txt does not exist.

Conclusion

The cp command is a fundamental tool in Bash for copying files and directories. By understanding its syntax and various options, you can effectively manage your files and directories. Whether you need to create a duplicate of a file or copy an entire directory, the cp command provides the necessary functionality to accomplish these tasks efficiently.