← Back to Bash Course | Chapter 9: File Testing & Filesystem | Lesson 9 of 13

cp, mv, rm

cp, mv and rm are like photocopying a page, moving a page to another folder, and putting a page in the shredder. Each one handles files in a different way.

In this page:

  1. cp, mv, rm
Syntax
bash
cp source destination
mv source destination
rm [-r] file_or_directory

cp, mv, rm

cp copies files, mv moves or renames them, and rm deletes them. cp -r and rm -r operate recursively on directories. These are the fundamental filesystem manipulation commands used constantly in shell scripts.

Warning: rm -rf deletes recursively without confirmation — a typo in the path can destroy far more than intended.

Example: cp, mv, rm

bash
#!/bin/bash
echo "original" > original.txt

cp original.txt copy.txt
mv copy.txt renamed.txt

ls original.txt renamed.txt

rm renamed.txt
echo "renamed.txt removed"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Running rm -rf with an empty variable, as in rm -rf "$dir/", which can delete the wrong path.
  2. Overwriting files with cp or mv with no -i or -n.
  3. Forgetting -r when copying a directory.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.