A2oz

How to Copy Files from One Directory to Another in Terminal?

Published in Command Line 2 mins read

You can use the cp command in your terminal to copy files from one directory to another.

Using the cp command

The cp command takes two arguments: the source file or directory and the destination directory. Here's the basic syntax:

cp [source] [destination]

Example:

To copy a file named document.txt from the current directory to a directory named backup, you would use the following command:

cp document.txt backup/

Copying Multiple Files

To copy multiple files, you can use wildcards. For example, to copy all .txt files from the current directory to the backup directory, you would use:

cp *.txt backup/

Copying Entire Directories

To copy an entire directory and its contents, you can use the -r (recursive) flag. For example, to copy the data directory and all its contents to the backup directory, you would use:

cp -r data backup/

Note: This will create a new directory named data within the backup directory, containing all the files and subdirectories from the original data directory.

Overwriting Files

By default, the cp command will not overwrite existing files in the destination directory. If you want to overwrite existing files, you can use the -f (force) flag.

Example:

cp -f document.txt backup/

This will overwrite any existing file named document.txt in the backup directory.

Additional Tips

  • Use absolute paths: If you are copying files between directories on different drives or in different parts of your file system, it is best to use absolute paths. This ensures that the command will work correctly regardless of your current working directory.
  • Check for errors: After running the cp command, check the output for any error messages. This will help you identify any problems that may have occurred during the copy process.
  • Use mv for moving files: If you want to move a file or directory from one location to another, you can use the mv command. This will delete the original file or directory from its source location.

Related Articles