Common Linux Commands Notes

1. Quick Reference Table for Linux Paths

Syntax Meaning Example Description
<span><span>/</span></span> 🟥 Root Directory <span><span>/etc/hosts</span></span> Starting point for all paths
<span><span>.</span></span> 🟩 Current Directory <span><span>./script.sh</span></span> Indicates “in the current directory”
<span><span>..</span></span> 🟨 Parent Directory <span><span>../file.txt</span></span> Parent directory of the current directory
<span><span>~</span></span> 🟦 Current User’s Home Directory <span><span>~/docs</span></span> Equivalent to <span><span>/home/username</span></span>
<span><span>~user</span></span> 🟪 Specified User’s Home Directory <span><span>~root</span></span> Indicates <span><span>/root</span></span>
Absolute Path 🟧 Complete path starting from <span><span>/</span></span> <span><span>/home/user/file.txt</span></span> Uniquely identifiable by the system
Relative Path 🟩 Path relative to the current directory <span><span>docs/file.txt</span></span> Depends on the current location
<span><span>-</span></span> 🟦 Last Directory <span><span>cd -</span></span> Switch between two directories

2. File and Directory Operations

  • <span><span>-</span></span> Parameters start with this symbol
  • Writing <span><span>name "*.py"</span></span> → The system treats it as a regular filename parameter, not a condition
  • Writing as <span><span>-name "*.py"</span></span> → Represents “conditional option” that tells <span><span>find</span></span> to match by name

In other words, <span><span>-</span></span> Parameters start with this symbol are similar to <span><span>ls -l</span></span> and <span><span>rm -r</span></span> commands.

2.1 ls – List Directory Contents

ls                    # List files in the current directory
ls -l                 # Detailed information (permissions, size, time, etc.)
ls -a                 # Show hidden files
ls -la                # Combined usage
ls -lh                # Human-readable file sizes

“l for detailed, a for all, h for human-readable, t for time, r for reverse”

2.2 cd – Change Directory

cd /path/to/directory  # Change to specified directory
cd ..                  # Go back to the parent directory
cd ~                   # Return to home directory, just typing cd works too
cd -                   # Return to the last directory

2.3 pwd – Display Current Directory Path

pwd                    # Display full path

2.4 mkdir – Create Directory

mkdir is for creating directories, not files

<span><span>mkdir</span></span> Name Origin

  • mk → make (create)
  • dir → directory (directory)
  • Combined, it means make directory → Create a directory.

<span><span>-p</span></span> Meaning

  • <span><span>-p</span></span> = parents (parent directory)
  • Meaning:If the parent directory does not exist, create it as well; and if the directory already exists, no error will be reported.
mkdir dirname          # Create a single directory
mkdir -p path/to/dir   # Recursively create multi-level directories
mkdir dir1 dir2 dir3   # Create multiple directories at once

2.5 rm – Remove Files/Directories

  • <span><span>rm</span></span> = remove

  • Function: Remove files or directory links.

  • <span><span>-r</span></span>recursive (recursively) → Deletes everything down the line, including files and subdirectories in the directory.

    <span><span>-f</span></span>force (force) → Force delete, will not ask for confirmation, nor will it prompt for non-existent files.

In the Unix/Linux world, most commands are abbreviations of English words, <span><span>rm</span></span> is short for remove (to remove, delete).

rm filename            # Remove file
rm -r dirname          # Recursively remove directory
rm -f filename         # Force delete (no prompt)
rm -rf dirname         # Forcefully recursively delete directory
rm *.txt               # Remove all .txt files

2.6 cp – Copy Files/Directories

<span><span>cp</span></span> = copy (to copy)

This is the abbreviation style of early Unix system commands: take the first two letters of the word, short and easy to type.

<span><span>-p</span></span> = preserve (to keep/preserve)

Purpose: When copying files, preserve the original file’s attributes, including:

  • Modification time (mtime)
  • Access time (atime)
  • Permissions (rwx)
  • Owner and group
cp file1 file2         # Copy file.
cp test.txt backup.txt   # Copy and name the new file backup.txt
cp file /path/to/dest  # Copy to specified directory
cp -r dir1 dir2        # Recursively copy directory
cp -p file1 file2      # Preserve original file attributes

2.7 mv – Move/Rename Files

<span><span>mv</span></span> = move (to move)

Function:

  1. Move files/directories to a new location
  2. Rename files/directories
mv oldname newname     # Rename file, works for directories too
mv file /path/to/dest  # Move file, directories can also be moved
mv dir1 dir2           # Move or rename directory

2.8 find – Find Files

1. Find by Name

find . -name "*.txt"         # Find .txt files in the current directory
find /path -name "*.py"      # Find .py files in the specified path
  1. Find by Type

Without adding <span><span>-type</span></span>, <span><span>find</span></span> will only match based on name, size, etc., possibly including directories, symbolic links, etc.

find . -type f -name "*.py"  # Find Python files in the current directory
find /path -type d -name "test"  # Find directory named test in the specified path

📖 Common <span><span>-type</span></span> Types**

  • <span><span>-type f</span></span> → Regular file (file)
  • <span><span>-type d</span></span> → Directory (directory)
  • <span><span>-type l</span></span> → Symbolic link (symlink)
  • <span><span>-type s</span></span> → Socket (socket)
  • <span><span>-type b</span></span> → Block device (block device)
  • <span><span>-type c</span></span> → Character device (character device)
  1. Find by Size
find . -size +100M           # Find files larger than 100MB in the current directory
find /path -size -10M        # Find files smaller than 10MB in the specified path

Starting from the current directory, find files that are larger than 100MB.

  • <span><span>+100M</span></span> → Greater than 100MB
  • <span><span>-100M</span></span> → Less than 100MB
  • <span><span>100M</span></span> → Exactly 100MB

4. Find by Time

find . -mtime -7             # Find files modified within the last 7 days in the current directory
find /path -mtime +7         # Find files modified more than 7 days ago in the specified path

Starting from the current directory, find files that are larger than 100MB .

  • <span><span>+100M</span></span> → Greater than 100MB
  • <span><span>-100M</span></span> → Less than 100MB
  • <span><span>100M</span></span> → Exactly 100MB

3. File Viewing and Editing

Command Function Features
<span><span>cat</span></span> Display entire file Prints all at once, suitable for small files
<span><span>more</span></span> Paginated display Can only scroll down, limited functionality
<span><span>less</span></span> Paginated display Can scroll up and down, search, most powerful functionality

3.1 cat – Display File Content

Full name:concatenate (verb, to connect, to concatenate).

In Unix/Linux, <span><span>cat</span></span> was originally used to concatenate the contents of multiple files and output them to the terminal.

Later, because using <span><span>cat file.txt</span></span> can directly display content, many people began to use it as the command to “view files”.

cat filename           # Display entire content of the file, not applicable for directories
cat file1 file2        # Display multiple files at once
cat -n filename        # Display line numbers and show entire content of the file

3.2 less/more – Paginated Viewing

<span><span>1 less</span></span>

  • The name comes from the English proverb “less is more” (less is more).

  • It is named as an improved version of <span><span>more</span></span>:

    • <span><span>more</span></span> → Can only scroll down, limited functionality
    • <span><span>less</span></span> → More powerful, can scroll up and down, search, jump
  • So the author humorously named it <span><span>less</span></span>, meaning “less is stronger than more”.

less filename          # Paginated viewing (recommended)

The file will not be printed all at once to the screen, but displayed page by page.

You can use shortcut keys to scroll, search:

  • <span><span>space</span></span> → Next page
  • <span><span>b</span></span> → Previous page
  • <span><span>/keyword</span></span> → Search
  • <span><span>q</span></span> → Exit

<span><span>2 more</span></span> means “show more content”.

(1) Compared to less, it can show the reading progress

more filename          # Paginated viewing
# In less: q to exit, / to search, n for next, N for previous

(2) Can query keywords

After entering <span><span>more</span></span>, you can operate like this:

  • <span><span>/keyword</span></span> → Search down for “keyword”

    • Example:

      /hello
      

      Will find the first “hello” in the remaining content and stop there, just type and press enter to query.

  • <span><span>n</span></span> → Find the next match (abbreviation for next)

  • <span><span>q</span></span> → Exit

3.3 head/tail – View File Start/End

📌<span><span>head</span></span>

  • English:head = head
  • Meaning: Display the “first few lines” of the file
  • Defaults to 10 lines, can use <span><span>-n</span></span> to specify the number of lines.

📌 <span><span>tail</span></span>

  • English:tail = tail
  • Meaning: Display the “last few lines” of the file
  • Defaults to 10 lines, can use <span><span>-n</span></span> to specify the number of lines.

📌 <span><span>tail -f</span></span>

  • <span><span>-f</span></span> = follow (to follow)
  • Meaning: Continuously “follow” changes at the end of the file, commonly used for log files.
head filename          # Display first 10 lines, file with extension
head /tmp/demo.txt     # File without extension
head /tmp/demo
head -n20 filename    # Display first 20 lines
tail filename          # Display last 10 lines
tail -n50 filename    # Display last 50 lines
tail -f filename       # Real-time monitor file changes

3.4 grep – Text Search

<span><span>grep</span></span> is used to search for text within file contents.

📌 <span><span>grep</span></span> name origin

  • <span><span>grep</span></span> comes from a command in the ed editor:

    g/re/p
    

    Meaning:globally search for a regular expression and print 👉 Globally search for a regular expression and print.

  • Later it was simplified to the command name <span><span>grep</span></span>.

📖 Common parameters’ English origins

  • <span><span>-r</span></span> = recursive👉 Recursively search all files in the directory.
  • <span><span>-i</span></span> = ignore case👉 Ignore case.
  • <span><span>-n</span></span> = number👉 Display line numbers of matching lines.
  • <span><span>-v</span></span> = invert match👉 Invert match → Display lines that do “not match”.
grep "pattern" filename        # Search in file, e.g.: grep "Linux" /tmp/demo.txt  Of course, some files have no extension /tmp/demo directly is this
grep -r "pattern" directory    # Recursively search directory, e.g.: grep -r "Linux" /tmp/mydocs
grep -i "pattern" filename     # Ignore case
grep -n "pattern" filename     # Display line numbers
grep -v "pattern" filename     # Display non-matching lines "Display non-matching lines" = Exclude lines containing keywords, only show the remaining lines.

4. File Permissions and Attributes

4.1 chmod – Change File Permissions

<span><span>1 chmod</span></span> name origin

  • <span><span>chmod</span></span> = change mode
  • In Linux/Unix, file permissions are called mode, such as read r, write w, execute x.
  • <span><span>chmod</span></span> is the command to change file permission mode.

2 Usage of chmod

r = 4 (read), w = 2 (write), x = 1 (execute), 0 = — (no permission)

Numbers = r+w+x summed to get permissions, for example 7=rwx, 6=rw-, 5=r-x, 4=r– …

Three digits represent:u = user/owner (file owner), g = group (file group), o = others (other people)

chmod 755 filename     # Set permissions in numeric format
chmod +x filename      # Add execute permission
chmod -w filename      # Remove write permission
chmod u+x filename     # Add execute permission for user

Permission Explanation:

  • 4=read(r), 2=write(w), 1=execute(x)
  • 755 = rwxr-xr-x (user can read, write, execute; group and others can read, execute)

4.2 chown – Change File Owner

chown user filename           # Change owner
chown user:group filename     # Change owner and group
chown -R user:group dirname   # Recursively change directory

5. Process Management

<span><span>ps aux</span></span> and <span><span>ps -ef</span></span> and top differences

<span><span>ps aux</span></span> and <span><span>ps -ef</span></span> = Full list, lists all

<span><span>top</span></span> = Dynamic monitoring, prioritizes showing processes with high resource usage, remaining processes are also there but need to scroll to see.

5.1 ps – View Processes (Static)

<span><span>ps</span></span> defaults to showing processes in the current terminal (shell) → So you can only see 1~2, such as <span><span>bash</span></span> and the command you just entered <span><span>ps</span></span> itself.

Programs running in the current terminal can only be seen with <span><span>ps</span></span> in that terminal; in a new terminal, <span><span>ps</span></span> will not show those processes by default.

<span><span>ps aux</span></span> and ps will list all processes in the system → So there will be a lot.

<span><span>ps</span></span>process status displays process status.

<span><span>aux</span></span> → BSD style options:

  • <span><span>a</span></span> = all (all user processes)
  • <span><span>u</span></span> = user (show user information)
  • <span><span>x</span></span> = include processes without a terminal

<span><span>-ef</span></span> → System V style options:

  • <span><span>-e</span></span> = every (all processes)
  • <span><span>-f</span></span> = full (complete format, parent-child relationships, etc.)

<span><span>grep</span></span> → global regular expression print, filters specific processes in the output.

ps                     # Display current user processes
ps aux | grep process  # Find specific process
ps aux | grep keyword, usually the program's filename

ps aux                 # Display detailed information of all processes

Typical BSD style output, common columns include:

USER   PID  %CPU  %MEM  VSZ  RSS  TTY  STAT  START  TIME  COMMAND
  • <span><span>%CPU</span></span> → CPU usage percentage
  • <span><span>%MEM</span></span> → Memory usage percentage
  • <span><span>STAT</span></span> → Process status (e.g., R=running, S=sleeping, I=idling)
  • <span><span>START</span></span> → Start time
  • <span><span>TIME</span></span> → Cumulative CPU time

👉 Focus on resource monitoring (CPU, memory, status).

ps -ef                 # Another way to display all processes

Typical System V style output, common columns include:

UID   PID   PPID   C   STIME   TTY   TIME   CMD
  • <span><span>UID</span></span> → User of the process
  • <span><span>PID</span></span> → Process ID
  • <span><span>PPID</span></span> → Parent Process ID (shows parent-child relationships)
  • <span><span>C</span></span> → CPU usage rate
  • <span><span>STIME</span></span> → Start time
  • <span><span>TIME</span></span> → Cumulative CPU time

👉 Focus on process relationships (parent-child structure, start time).

5.2 top – Real-time View of System Processes (Dynamic, Tabular Display)

<span><span>top</span></span> this name is commonly interpreted as:

  • Table Of Processes (process table)
top                    # Real-time display of process information
# In top: q to exit, k to kill process, M to sort by memory, P to sort by CPU

Can display all, needs scrolling to see

  1. Scroll left/right (to see more information columns)

    👉 Some fields (like the complete command CMD of the process) are too long, so you need this to see the full.

  • Press <span><span>→</span></span> (right arrow) → Move right to display more fields
  • Press <span><span>←</span></span> (left arrow) → Move left
  1. Scroll up/down (to see more processes)By default, <span><span>top</span></span> only displays one screen of processes (e.g., 40 lines), if there are many processes, you can:
  • <span><span>Shift + PgDn</span></span> (Page Down) → Next page
  • <span><span>Shift + PgUp</span></span> (Page Up) → Previous page

👉 This way you can see more than one screen of processes.

  1. Expand display line count
  • In the <span><span>top</span></span> interface, press <span><span>z</span></span> to switch to color mode, more intuitive.

  • Use <span><span>E</span></span> / <span><span>e</span></span> to switch units (KB, MB, GB).

  • You can also specify when starting <span><span>top</span></span>:

    top -n 1 -b | less
    

    👉 Here, <span><span>less</span></span> can scroll up and down to browse all process output.

5.3 kill – Terminate Process

kill PID               # Gracefully terminate process, equivalent to kill -15 PID   # Graceful exit (recommended to use first)
kill -9 PID            # Forcefully terminate process
killall process_name   # Kill all related processes by name
kill -1 PID    # Let the process reload configuration
kill -STOP PID # Suspend process
kill -CONT PID # Let the process continue

Suspend Process Function (Stop/Suspend):

Main purpose:

  1. Temporarily reduce server load:
  • When a program suddenly consumes full CPU, and you do not want to kill it directly.
  1. Cross-terminal / Cross-user process management
  • You started a program (like a training script) in terminal A.
  • You or an operations personnel can directly <span><span>kill -STOP PID</span></span> to pause it without running to terminal A.
  1. Debugging / Troubleshooting
  • If you want to analyze the state of a process, you can first <span><span>STOP</span></span> it → Stabilize at a certain moment without running.
  • After checking, you can then <span><span>CONT</span></span> to resume running.

  1. Temporarily release terminal (using in the same terminal)

  • You are running a long task in the terminal (like <span><span>python train.py</span></span> or <span><span>tail -f</span></span>), suddenly want to execute another command.
  • 👉 Press <span><span>Ctrl+Z</span></span> to suspend → The program pauses, and the terminal is released.
  • Prevent the process from continuing to run (a program started in one terminal, even if you use <span><span>kill</span></span> to stop or resume it in another terminal, this process still belongs to the terminal that originally started it; if you close that starting terminal, the process will also end.)

    • When a program occupies a lot of CPU, you do not want to kill it (for fear of losing data), but want to pause it first.
    • 👉 <span><span>kill -STOP PID</span></span>This will directly send the specified PID process a <span><span>SIGSTOP</span></span>, regardless of which terminal it was started in, it can be suspended.

    5.4 nohup – Run in Background

    <span><span>nohup</span></span> = no hang up → Allows the process to “survive independently”, even if the terminal is closed, the program will continue to run.

    nohup command &        # Run command in background, unaffected by terminal closure
    

    Long-running tasks

    • For example: model training, data import, log analysis, etc., which may take hours or even days.

    • If run directly in the terminal, SSH disconnection / computer sleep will cause the task to be interrupted.

    • 👉 Common usage:

      nohup python3 train.py > train.log 2>&1 & tail -f train.log   # Real-time view of logs
      

    <span><span>></span></span> train.log → Redirects standard output (stdout) to <span><span>train.log</span></span> file.

    <span><span>2>&1</span></span> → Redirects standard error (stderr) also to standard output (i.e., also written into <span><span>train.log</span></span>).

    • <span><span>1</span></span> = stdout, <span><span>2</span></span> = stderr
    • <span><span>2>&1</span></span> = Merges the output of 2 into 1 (merges error output and normal output.)

    <span><span>&</span></span> → Places the entire task in the background, allowing the terminal to immediately accept more commands.

    Logs = Content output to the terminal (stdout + stderr), saved to a file.

    The benefit is: even if the program runs for several days, if the terminal is closed, the content will not be lost, and can be traced back at any time.

    <span><span>nohup</span></span> → One-time tasks (throw in to run, collect logs). The downside is: cannot “re-enter” the program’s interactive interface like <span><span>tmux</span></span> /<span><span>screen</span></span> can, only automatically ends and checks terminal output in logs.

    <span><span>tmux/screen</span></span> → Long-term interactive tasks (disconnection and reconnection, multi-window collaboration).

    Big company habits: Operations/backend prefer <span><span>tmux/screen</span></span><span><span>, algorithms/data science prefer</span></span>nohup`.

    <span><span>screen</span></span>: An old tool (appeared in 1987), functional enough, suitable for simple scenarios.

    <span><span>tmux</span></span>: A modern alternative (2007), strong split-screen + management capabilities, more commonly used in big companies.

    6. System Information

    6.1 df – View Disk Usage

    <span><span>df</span></span> origin

    • Full name:disk free

    • Function : Displays disk usage of the file system (remaining space, total space, used space, etc.).

    • Literally means “disk free amount”.

    • <span><span>df -h</span></span> → Check if “disk space” is sufficient.

    • <span><span>df -i</span></span> → Check if “can create more files”.

    Disk is like a big warehouse:

    • Not enough space → Warehouse has no place to store goods.

    • Not enough inodes → Warehouse still has space, but the shelves (numbering) are used up, cannot register new goods.

      The value of inodes is: providing each file with an independent “ID card”, separating file metadata from content, facilitating efficient management and locating files by the file system.

    df                     # Display disk usage
    df -h                  # Human-readable display (GB, MB, etc.)
    df -i                  # Display inode usage information, showing inode usage (i.e., related to file count, not disk capacity).
    

    6.2 du – View Directory Size

    <span><span>du</span></span> full name is disk usage.

    • disk = disk
    • usage = usage
    du                     # Display current directory size
    du -h                  # Human-readable display
    du -s                  # Only display total
    
    du -sh *               # Display size of each folder in the current directory
    

    6.3 free – View Memory Usage

    free in English means free, available.

    free                   # Display memory usage
    free -h                # Human-readable display
    free -m                # Display in MB
    

    6.4 Other System Information Commands

    uname -a               # System information
    whoami                 # Current username
    who                    # Current logged-in users
    date                   # Display date and time
    uptime                 # System uptime and load
    

    7. Network Related

    7.1 ping – Test Network Connectivity

    ping google.com        # Test network connectivity
    ping -c 4 google.com   # Ping 4 times only
    

    7.2 wget/curl – Download Files

    wget http://example.com/file    # Download file
    curl -O http://example.com/file # curl download file
    curl -L url                     # Follow redirects
    

    7.3 ssh – Remote Login

    ssh user@hostname      # Remote login
    ssh -p port user@host  # Specify port
    

    7.4 scp – Remote Copy Files

    scp file user@host:/path/       # Copy file to remote
    scp user@host:/path/file ./     # Copy file from remote
    scp -r dir user@host:/path/     # Copy directory
    

    8. Compression and Decompression

    8.1 tar – Pack and Compress

    tar -czf archive.tar.gz dir/    # Create gzip compressed package
    tar -xzf archive.tar.gz         # Unzip gzip compressed package
    tar -tf archive.tar.gz          # View contents of compressed package
    tar -czf backup.tar.gz --exclude='*.log' dir/  # Exclude specific files
    

    8.2 zip/unzip

    zip -r archive.zip dir/         # Create zip compressed package
    unzip archive.zip               # Unzip zip file
    unzip -l archive.zip            # View zip contents
    

    9. Piping and Redirection

    9.1 Piping

    ls -l | grep ".txt"             # Filter .txt files
    ps aux | grep python            # Find python processes
    cat file | sort | uniq          # Sort and remove duplicates
    

    9.2 Redirection

    command > file                  # Output redirection to file (overwrite)
    command >> file                 # Append output to file
    command < file                  # Input from file
    command 2> error.log            # Error output redirection
    command &> all.log              # Redirect all output
    

    10. Common Combination Techniques

    10.1 Find Large Files

    find . -type f -size +100M | head -10
    du -ah . | sort -rh | head -20
    

    10.2 View Port Usage

    netstat -tulpn | grep :8080
    lsof -i :8080
    

    10.3 Batch Processing

    for file in *.txt; do mv "$file" "${file%.txt}.bak"; done  # Batch rename
    find . -name "*.log" -exec rm {} \;  # Batch delete log files
    

    10.4 System Monitoring

    watch -n 1 "ps aux | grep python"   # Refresh process information every second
    iostat 1                            # Monitor IO status
    

    11. Shortcuts

    • <span><span>Ctrl + C</span></span> – Terminate current command
    • <span><span>Ctrl + Z</span></span> – Suspend current command
    • <span><span>Ctrl + L</span></span> – Clear screen
    • <span><span>Ctrl + A</span></span> – Move cursor to the beginning of the line
    • <span><span>Ctrl + E</span></span> – Move cursor to the end of the line
    • <span><span>Ctrl + R</span></span> – Search command history
    • <span><span>!!</span></span> – Execute the last command
    • <span><span>!grep</span></span> – Execute the most recent grep command

    Tips

    • Use <span><span>man command</span></span> to view detailed help documentation for commands
    • Use <span><span>command --help</span></span> to view basic usage of commands
    • Make good use of the Tab key for auto-completion of filenames and commands
    • Use history to view command history

    Leave a Comment