In the last post we saw how to move around within directories, in this post we will see how to do file operations like copy, move, rename, etc.
So let’s get started
- To copy files and directories we use the “cp” command, with or without arguments.
cp -[arguments] [source] [dest]
– To copy a file named “cat.txt” from location “abc” to “xyz” and keep the file name same you can use the below command
#cp /abc/cat.txt /xyz/
– To copy the file and rename it you can mention the new name in the destination.
#cp /abc/cat.txt /xyz/dog
– To copy directories the syntax is similar:
#cp /abc /xyz/
This will copy the directory abc within the directory /xyz/
– To copy everything within a directory to another directory:
#cp /abc/* /xyz/
The cp command takes many arguments but the common ones are [-p -r -a and -v]
-p: This parameter will preserve the mode, ownership and timestamps of the file.
It will also try to preserve additional permissions like context and links.
-r or -R: This argument will copy the files recursively.
-a: This is the same as -dR --preserve=all
-v: This is verbose mode means it will show what is going on.
There are a lot more arguments so like earlier I will say, when in doubt refer the man pages.
#man cp - To move a file or directory you can use the command “mv“
– To move a file from /abc/cat.txt to /xyz/
#mv /abc/cat.txt /xyz/
– To move all files from one directory to another:
#mv /abc/* /xyz/
– To rename a file or directory, use the mv command in the same location:
#mv abc hij
This will rename the directory or file abc to hij.
The mv command also takes a lot of arguments, to explore them:
#man mv - To remove delete a file you can use the “rm" command and to delete a directory you can use the "rmdir" command.
“rmdir” command needs the directory to be empty, but you can use the argument "--ignore-fail-on-non-empty" to ignore the errors that is caused by non-empty directory.
#rmdir /abc
– To delete a file:
#rm file-a
– To delete a file recursively:
#rm -r /abc/
– To delete a file, but prompt before removing:
#rm -i /abc/
This is the default mode and the command should ask you before removing a file, depending on your distro.
– To delete a file forcibly:
#rm -f /abc/file-a
– You can combine these options as below:
#rm -fr /abc/
Note: Before using the “rm” command please be double sure and be careful as once the file is removed you will not be able to recover it and it is permanently gone. So make sure to be in the right directory and make sure you have typed the right file or directory name to delete. Best is to type the command in a notepad once and type it from there to the terminal.
– To explore more of the rm command:
#man rm
Well that’s it with the major file operations commands, we will keep seeing and exploring new ones as we go ahead.
Hope you liked this post, see you again in another one of blog.avoidingtech.com