3 Easy Ways to Copy Files and Directories in Linux

0
3 Easy Ways to Copy Files and Directories in Linux

Copying files and directories from the command line in Linux is a relatively simple procedure that you’ll most likely need to do at some point in your Linux career. Here are three commands that will help you copy files and directories in Linux, along with examples of how to use them.

cp

Copying files from the command line is a straightforward process. To copy a file or directory, use cp followed by the source directory you want to copy from, the destination directory you want it copied to, and the filename. The following will copy file.txt from your current directory to the documents folder of your home folder:

cp file.txt ~/documents/ The -r flag can be used with cp to recursively copy directories, meaning all contents inside of them will also be copied:

cp -r file.txt ~/documents/ ; cp -r src_dir/ dest_dir; cp –help; sudo cp –preserve=all src_dir/* dest_dir

mv

Mv is the simplest command for renaming files. The mv command will also move files from one location to another. To copy a file, you would use cp. To copy a directory, you would use cp -r. There are many more options available with these commands. Be sure to consult the man pages if you need further assistance. Don’t forget about: pwd (displays your current working directory), ls (lists all of the files in your current working directory), cd (changes directories), mkdir (creates new directories).

For example, let’s say we have a folder named test1. Inside that folder are two files named data1 and data2. If we wanted to rename our first file so it had no spaces (test 2) and put it inside our parent directory, we could type

rsync

rsync is a powerful program that allows you to copy or synchronize files or directories from one location to another. If you’re copying files over a network connection, rsync takes much less time than other types of transfers. With rsync, it’s possible to replace older files with newer ones without transferring all the new ones- just those that have changed since the last sync. It can also be used as an archiving tool by specifying an archive format on the command line. When used with -a (for archive), rsync will preserve permissions, group ownership, symbolic links, devices, owner and group id information, atime (time of last access) and mtime (time of last modification). Lastly if you want to transfer files but don’t want them to overwrite any existing files on your destination computer then use the –backup option for both source and destination.

Leave a Reply

Your email address will not be published. Required fields are marked *