Cheatsheets:LinuxCLI/FileOps: Difference between revisions

From Wikibase
Jump to navigation Jump to search
Line 5: Line 5:
New to the command line? Every command here has a built-in manual — try <syntaxhighlight lang="bash" inline>man ls</syntaxhighlight> or [https://tldr.sh tldr] for short examples; [https://explainshell.com explainshell.com] annotates any command line.
New to the command line? Every command here has a built-in manual — try <syntaxhighlight lang="bash" inline>man ls</syntaxhighlight> or [https://tldr.sh tldr] for short examples; [https://explainshell.com explainshell.com] annotates any command line.


== Basic example: a small file workflow ==
== Basic example ==


<syntaxhighlight lang="bash" line highlight="2,3,5,6" copy>
<syntaxhighlight lang="bash" copy>
pwd                        # where am I?
pwd                        # where am I?
mkdir -p notes/drafts      # create nested directories
mkdir -p notes/drafts      # create nested directories

Revision as of 12:12, 23 August 2026

Languages: English · français · Esperanto

Quick reference for smart people — part of our Linux cheatsheets collection.

The everyday Linux command-line file operations: navigate, create, copy, move, inspect, search, and archive files.

New to the command line? Every command here has a built-in manual — try man ls or tldr for short examples; explainshell.com annotates any command line.

Basic example

pwd                        # where am I?
mkdir -p notes/drafts      # create nested directories
cd notes/drafts
touch todo.txt             # create an empty file
cp todo.txt todo.bak       # copy
mv todo.bak ../todo.md     # move + rename in one step
ls -la                     # inspect the results
head -n 3 todo.txt         # peek at the contents
pwd              # print the current directory
cd dir           # enter dir
cd ..            # go up one level
cd ~             # home directory
cd -             # previous directory

ls — the workhorse:

ls [options] [dir]   # list directory contents
ls *.txt             # glob: only matching names
Option Effect
-l long format: permissions, owner, size, date
-a hidden files (dotfiles)
-h human-readable sizes (combine with -l)
-R recurse into subdirectories
-t sort by modification time, newest first

Creating & removing

mkdir newdir                      # create a directory
mkdir -p dir/subdir/newsubsubdir  # create parents as needed
mkdir -m 755 dir                  # set permissions at creation
rmdir emptydir                    # remove an EMPTY directory
rmdir -p dir/subdir/emptysubdir   # ... and its empty parents
touch file.txt                    # create an empty file (or refresh its mtime)
touch -t 202501011200 f           # set a specific timestamp
rm file.txt                       # delete a file
rm -r dir/                        # delete a directory and its contents
rm -f file                        # never prompt, ignore missing files
rm -i file                        # prompt before each delete

rm -rf is irreversible — there is no trash bin. Double-check the path (and your current directory with pwd) before deleting recursively.

Copying & moving

cp file.txt backup.txt      # copy a file
cp -r src/ dest/            # copy a directory recursively
cp -a src/ dest/            # recursive + preserve attributes
cp -i file.txt dest/        # prompt before overwriting
cp file1 file2 dest/        # several files into a directory
mv file.txt newname.txt     # rename
mv file.txt dir/            # move into a directory
mv -i file.txt dir/         # prompt before overwriting
mv src/ dest/               # move/rename a directory

Viewing files

cat file.txt            # print the whole file
cat file1 file2         # concatenate, in order
cat -n file.txt         # with line numbers
less file.txt           # scrollable pager: /search, g/G jump,f/b move forward/backward one page, q quit
head -n 5 file.txt      # show first 5 lines of a file. If no -n parsed, default is 10
tail -n 50 app.log      # show last 50 lines of a file. If no -n parsed, default is 10
tail -f app.log         # follow a growing log, Ctrl+C to stop

Searching

grep — search inside files:

grep [options] pattern file   # print matching lines
Option Effect
-i case-insensitive
-n include line numbers
-v invert: lines that do NOT match
-r search a directory recursively
-l only filenames with matches
-c count matching lines
-E extended regex, e.g. grep -E 'a|b' file

find — search by name, type, age, size:

find . -name "*.py"                  # by name (glob)
find /home -type f                   # only files
find /home -type d                   # only directories
find . -mtime -7                     # modified in the last 7 days
find . -size +100M                   # larger than 100 MB
find . -name "*.log" -delete         # delete matches
find . -name "*.tmp" -exec <some-commands> {} \;  # run a command on each match

locate — faster index-based search:

locate file.txt    # instant filename lookup
locate folder/subfolder    # instant partial path lookup
sudo updatedb           # refresh the index (requires root permission)

locate searches an index refreshed by updatedb — files created since the last update are invisible to it. find is slower but always up to date.

Permissions & ownership

chmod — change file/folder permissions.

chmod 755 script.sh     # rwxr-xr-x
chmod 644 file.txt      # rw-r--r--
chmod u+x script.sh     # add execute for the owner
chmod -R 755 dir/       # recursive
chown alice file.txt        # change owner
chown alice:dev file.txt    # owner and group
chown -R alice:dev dir/
chgrp dev file.txt       # change group only
stat file.txt            # perms, size, timestamps, inode
file archive.tar         # detect the file type

On GNU Linux, there are two notations for file permissions.

  • Numeric: three digits representing permissions for owner|owner's group|others
    • Each digit is an arithmetic sum of all accorded permissions: 4:read, 2:write, 1:execute
  • Symbolic: mostly used to add/remove a single permission.
    • r:read, w:write, x:execute
    • u=owner, g=owner's group, o=others, a=all
    • +add, - to remove, = to set permission to exactly the given value.

Below are some common file permissions:

Numeric Symbolic
7 rwx
6 rw-
5 r-x
4 r--

You can read permissions of a given directory and its content with ls -l.

The command output will be something like this:

drwxr-xr-x  2 rongzhou rongzhou    4096 Aŭg 20 16:19 9781474271325.sdr
-rw-rw-r--  1 rongzhou rongzhou    1758 Mar 10 15:26 antaurigardo.html
drwxrwxr-x  4 rongzhou rongzhou    4096 Mar 13 14:28 Arduino
drwxr-xr-x  4 rongzhou rongzhou    4096 Jul 22 12:20 Bildujo

The first column is permission.

  • There are always 10 chars.
  • The first char is always d for directories and - for files.
  • char 2-4 are permissions for owner in symbolic notation
  • char 5-7 are permissions for owner's group
  • char 8-10 are permissions for others

Disk usage

du -sh dir/              # total size of a directory, human-readable
du -sh *                 # size of each item
du -h --max-depth=1 dir/ # per subdirectory
df -h                    # free space per mounted filesystem
df -h .                  # ... only for the filesystem holding the current dir
ln target hardlink          # hard link: same file, another name
ln -s target symlink        # symbolic link: points to a path
ln -s /usr/local/bin/tool ~/bin/tool

Hard links cannot span filesystems or point at directories. ls -l shows a symlink's target with ->.

Archives

tar

tar -czf archive.tar.gz dir/       # create a gzipped archive
tar -xzf archive.tar.gz            # extract (compression auto-detected)
tar -tzf archive.tar.gz            # list contents
tar -xzf archive.tar.gz -C dest/   # extract into a directory
tar -cjf archive.tar.bz2 dir/      # bzip2 instead of gzip
Option Effect
-c create an archive
-x extract
-t list contents
-f the archive file name — always followed by the archive
-z gzip compression → .tar.gz
-j bzip2 compression → .tar.bz2
-v verbose: list each file as it is processed
-C change to a directory before extracting

zip / unzip:

zip -r archive.zip dir/     # zip a directory recursively
zip archive.zip a.txt b.txt # zip specific files
unzip archive.zip           # extract
unzip -l archive.zip        # list contents
unzip archive.zip -d dest/  # extract into a directory
unzip -o archive.zip        # overwrite without asking

Text utilities

sort file.txt            # sort lines alphabetically
sort -n file.txt         # numeric sort
sort -r file.txt         # reverse
sort -u file.txt         # unique lines
sort -k2 file.txt        # sort by the 2nd field
diff file1 file2         # line-by-line differences
diff -u file1 file2      # unified diff (patch format)
diff -r dir1 dir2        # compare directories
cmp file1 file2          # byte compare: report first difference
echo "hello"             # print text
echo -n "no newline"     # omit the trailing newline
echo "hi" > file.txt     # overwrite a file with output
echo "hi" >> file.txt    # append to a file

> overwrites, >> appends — one character decides whether an existing file survives.

Further reading