mkdir / rm / cp / mv
Creating and removing files and directories with mkdir, rmdir, rm, cp, mv. The safe defaults and the destructive flags.
Linux — mkdir, rm, cp, mv
EXAMPLE
# ===== Create =====
mkdir foo # one dir
mkdir -p foo/bar/baz # parents as needed (the common form)
mkdir -m 700 secret # set perms at creation
# Multiple at once:
mkdir -p dist/{js,css,images}
# Create a file:
touch hello.txt
touch -t 202404101200 hello.txt # set mtime
# ===== Remove =====
rm file.txt # remove a file (PROMPTS only with -i)
rm -i file.txt # prompt before each
rm -f file.txt # force; no prompt, no error if missing
rmdir foo # remove EMPTY dir
rm -r foo # remove dir + contents (DESTRUCTIVE)
rm -rf foo # nuclear; no prompt, no errors
# ===== Copy =====
cp src.txt dst.txt
cp -a srcdir dstdir # archive: recursive + preserve perms/times/links
cp -v src.txt dst.txt # verbose
cp -i src.txt dst.txt # prompt before overwrite
cp -n src.txt dst.txt # no clobber (do not overwrite)
# Hard / soft links:
ln src.txt link.txt # hard link
ln -s src.txt symlink.txt # symlink
# ===== Move / rename =====
mv old.txt new.txt # rename
mv file.txt dir/ # move into dir
mv -i a b # prompt before overwrite
mv -n a b # no clobber
# Bulk rename with shell expansion:
for f in *.jpeg; do mv "$f" "${f%.jpeg}.jpg"; done
# ===== Safe defaults =====
# Aliases worth setting in your shell rc:
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Then use \rm if you specifically want non-interactive (or 'command rm').
# ===== Permissions vs ownership =====
chmod 644 file # rw-r--r--
chmod 755 dir # rwxr-xr-x (common for dirs)
chmod u+x script.sh # add execute to user
chmod -R 755 dir # recursive
chown user:group file
chown -R user:group dir
# Numeric reminders:
# r=4, w=2, x=1
# 7 = rwx, 6 = rw-, 5 = r-x, 4 = r--, 0 = ---
# ===== Find + delete safely =====
find . -type f -name '*.tmp' -print # preview FIRST
find . -type f -name '*.tmp' -delete # delete (only after the preview!)
# ===== Where to be careful =====
# - rm -rf / : destroys everything reachable
# - rm -rf $VAR/* : if VAR is empty -> rm -rf /*
# - Symlink + rm -r : may follow into shared content (use rm -r --preserve-root)
# - sudo rm without checking the path
# ===== Patterns to internalise =====
# - mkdir -p for nested dirs
# - rm -ri for interactive recursive
# - Verify with ls + find BEFORE removing
# - Keep a habit: ls, ls, ls, then rm
# ===== Pitfalls =====
# - 'rm $DIR/*' with an empty DIR
# - Glob expansion: rm * .txt (note the space)
# - Quoting filenames with spaces
# - Forgetting that rm does not go to a recycle bin
Why it matters
mkdir -p, rm with care, cp / mv with -i defaults, and chmod / chown with numeric perms. The destructive flags (-r, -f, --no-preserve-root) need a second look every time. ls before rm is a cheap habit that has saved many systems.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…