Moving and deleting files and folders

To move a file or folder we can use the same command, called mv. It takes two arguments and it's also the command we need to issue when we want to rename a file or folder. This sounds handy at first, but also means we have to be extra careful. Here's how you move a file or folder from the current directory into the moved folder

command line
mv ./folder ./moved/folder

Now as mentioned above, the same command is used to rename files and folders, so if we change its name in the destination (second argument) it will be moved and renamed, like below. This can be desired but oftentimes it's not, so always double-check to make sure your files end up where you want them to be.

command line
mv ./folder ./moved/changed-folder-name

Sometimes we want to move all of the content of a folder and need to copy all sub-folders and files over as well — we want a recursive copy. In order to achieve that with mv, we can provide the -R flag and use the wildcard operator * to recursively select all files and folders inside a directory

command line
mv source/* destination

How to delete things on the command line

It's getting even more dangerous from here on out because the remove command rm not only lets us delete single files, but also takes arguments that let us recursively remove everything inside a folder. Let's take a look at some examples, removing a single file or folder as well as removing multiple files by extension

command line
rm filename
rm -f foldername
rm *.txt

Notice the -f flag for deleting a folder? That's the force option, which is required to remove folders and skip prompts Just like recursively copying files and folders, we can also recursively remove everything inside a folder

command line
rm -rf foldername

On being cautious when deleting things

A lot of developers have some kind of war story about almost or actually removing large parts of their filesystem because a rm command went wrong. In order to prevent this — besides double checking your command — there is an option -i that makes your deletions interactive and prompts you for every file that it's going to delete. While that's not feasible for large amounts of files, it can be very helpful when crafting more complicated patterns like below, where we're looking to delete every file that starts with the pattern 'trash_' and want to be extra careful to see if our command is correct.

command line
find . -name 'trash_*' -exec rm -i \;
remove ./trash_test.txt? n
remove ./trash_test2.txt? y
More on how to use find and exec at a later point in this course