CLI 命令行界面完全指南

CLI 命令行界面完全指南 | CLI Command Line Interface Guide

一、什么是 CLI

CLI(Command Line Interface,命令行界面)是一种通过纯文本命令与计算机交互的方式。与使用鼠标点击图形界面(GUI)不同,CLI 要求用户在终端中输入文字指令,计算机执行后返回文本结果。

核心组成要素

要素说明示例
终端 / Terminal接收和显示文本的窗口程序Windows Terminal、iTerm2
Shell解释和执行命令的程序PowerShell、bash、zsh
命令 / Command告诉计算机执行什么操作cdlsgit
参数 / Argument命令操作的目标对象文件名、路径、URL
选项 / Option (Flag)修改命令行为的开关-h--help-f

历史背景

在 20 世纪 60-80 年代,CLI 是计算机唯一的交互方式。图形界面(GUI)普及后,CLI 逐渐退居幕后,但在以下领域仍然不可替代:

  • 软件开发 — 代码编译、测试、版本控制、依赖管理
  • 服务器运维 — 远程管理无图形界面的服务器
  • 数据科学 — Python 虚拟环境、pip 包管理、Jupyter 启动
  • DevOps / CI/CD — 自动化部署脚本、Docker 操作

二、CLI 与 GUI 的区别

维度CLI(命令行)GUI(图形界面)
交互方式键盘输入文本命令鼠标点击、拖拽
学习曲线较陡,需记忆命令平缓,所见即所得
操作效率熟练后极快(批量/自动化)适合简单、偶尔的操作
可重复性可将命令写入脚本自动执行难以精确复制步骤
资源消耗极低,无图形渲染开销较高
远程操作SSH 原生支持需远程桌面/VNC
精度完全精确,无歧义依赖 UI 设计
核心观点 CLI 和 GUI 并非对立关系。GUI 适合探索和日常使用,CLI 适合精确控制和自动化。专业开发者通常两者并用

三、常见 CLI 程序(Shell)

Shell 是”命令解释器”,负责读取用户输入的命令并交给操作系统执行。不同操作系统提供不同的 Shell:

Shell平台特点提示符示例
cmd.exeWindowsWindows 传统命令行,功能基础C:\Users\xxx>
PowerShellWindows macOS Linux微软现代 Shell,支持管道、对象、脚本PS C:\Users\xxx>
bashmacOS Linux最通用的 Unix Shell,几乎所有服务器默认user@host:~$
zshmacOSmacOS Catalina 起默认 Shell,插件生态丰富(Oh My Zsh)user@mac ~ %
fish跨平台友好的自动补全和语法高亮user@host ~>

Windows 用户的选择建议

Windows 提供三种常用终端:

cmd.exe

最基础,兼容老旧脚本。不支持现代特性(如管道对象、别名),不推荐作为日常主力

PowerShell(推荐)

功能强大,支持 lscd 等 Unix 风格命令,原生处理 JSON/XML,Windows 开发首选

WSL / Git Bash

在 Windows 中运行 Linux 环境。适合需要 Linux 命令的场景(如 shell 脚本、Docker)。

Windows Terminal

微软官方终端应用,支持多标签、自定义主题。可同时运行 cmd / PowerShell / WSL。

四、如何打开 CLI

平台方式说明
WindowsWin + R → 输入 powershell → 回车快速打开 PowerShell
Windows右键开始菜单 → “Windows Terminal” 或 “终端”打开多标签终端
Windows在文件资源管理器地址栏输入 powershell在当前目录打开终端
Windows右键文件夹 → “在终端中打开”Win11 原生支持
macOSCmd + 空格 → 搜索 “Terminal”打开终端(zsh)
macOSFinder → 应用程序 → 实用工具 → 终端手动导航
LinuxCtrl + Alt + T大多数发行版的快捷键
打开后的第一件事 输入以下命令验证 Shell 类型:
$echo $SHELL
或在 PowerShell 中:
PS>$PSVersionTable

五、命令的基本结构

每一条 CLI 命令都遵循统一的语法格式:

$命令 [选项] [参数]

各部分的含义:

部分作用示例
命令要执行的程序或操作gitpythonpipnpm
选项(短格式)以单个 - 开头,控制行为-h-v-f
选项(长格式)以双 -- 开头,含义更明确--help--version
参数命令操作的对象文件名、路径、URL、文本

实际拆解示例

$pip install –upgrade numpy
部分内容含义
命令pipPython 包管理工具
子命令install执行安装操作
选项--upgrade升级已安装的包到最新版
参数numpy要安装/升级的包名

更多示例

# 查看帮助(几乎所有 CLI 工具都支持)
git --help
python --help
pip --help

# 查看版本
python --version
node --version

# 多个短选项可合并
ls -a -l -h     # 等价于
ls -alh

# 长选项和短选项等价
pip install -r requirements.txt
pip install --requirement requirements.txt
救命技巧 忘记命令怎么用时,随时输入 命令 --help命令 -h。这几乎适用于所有 CLI 工具。例如 git --helpdocker --helppytest --help

六、文件系统导航

CLI 操作的第一步是学会在文件系统中移动。以下命令在所有平台通用(PowerShell 同样支持):

6.1 查看当前路径

$pwd
/home/user/projects/my-app

6.2 列出目录内容

$ls
file1.txt  folder_a  README.md  src/

常用选项:

选项含义Windows (cmd) 等价
ls -l详细列表(权限、大小、时间)dir
ls -a显示隐藏文件(以 . 开头的文件)dir /a
ls -la详细列表 + 隐藏文件dir /a
ls -lh人类可读的文件大小(KB/MB)

6.3 切换目录

$cd /home/user/projects
# 进入子目录
cd src

# 返回上一级目录
cd ..

# 返回上两级
cd ../..

# 回到用户主目录
cd ~          # Linux/macOS
cd %USERPROFILE%    # Windows (cmd)
cd $HOME     # PowerShell

# 回到上一次所在的目录
cd -
Windows 路径写法 Windows 使用反斜杠 \(如 C:\Users\xxx),但 PowerShell 和现代工具也支持正斜杠 /(如 C:/Users/xxx)。建议统一使用正斜杠以保持跨平台一致性。

七、文件与目录操作

7.1 创建目录

# Linux / macOS / PowerShell
mkdir new_folder

# 创建多级目录(父目录不存在时自动创建)
mkdir -p project/src/utils     # Linux/macOS
New-Item -ItemType Directory -Force -Path project/src/utils  # PowerShell

7.2 创建 / 写入文件

# 用 touch 创建空文件(Linux/macOS/PowerShell 均可)
touch config.json

# 用 echo 写入内容(> 覆盖,>> 追加)
echo "Hello" > hello.txt
echo "World" >> hello.txt

7.3 复制文件 / 目录

# Linux / macOS
cp file1.txt file2.txt          # 复制文件
cp -r folder_a folder_b          # 递归复制目录

# Windows (cmd)
copy file1.txt file2.txt
xcopy folder_a folder_b /E /I

# PowerShell
Copy-Item file1.txt file2.txt
Copy-Item -Recurse folder_a folder_b

7.4 移动 / 重命名

# Linux / macOS
mv old_name.txt new_name.txt     # 重命名
mv file.txt folder/              # 移动到目录

# Windows (cmd)
move old_name.txt new_name.txt

# PowerShell
Move-Item old_name.txt new_name.txt
Move-Item file.txt folder/

7.5 删除文件 / 目录

警告 CLI 中没有”回收站”机制,rm / del 命令删除的文件无法恢复。务必谨慎操作,尤其是 rm -rf
# Linux / macOS
rm file.txt                      # 删除文件
rm -r folder/                    # 递归删除目录及内容
rm -rf folder/                   # 强制递归删除(不询问确认)

# Windows (cmd)
del file.txt
rmdir /s /q folder

# PowerShell
Remove-Item file.txt
Remove-Item -Recurse -Force folder

八、文件查看与编辑

8.1 查看文件内容

# 查看全部内容(小文件)
cat file.txt      # Linux/macOS/PowerShell
type file.txt     # Windows cmd
Get-Content file.txt  # PowerShell 完整写法

# 分页查看(大文件)
less file.txt     # Linux/macOS,按 q 退出
more file.txt     # Windows cmd

# 查看前 N 行
head -20 file.txt
Get-Content file.txt -Head 20   # PowerShell

# 查看后 N 行
tail -20 file.txt
Get-Content file.txt -Tail 20   # PowerShell

# 实时追踪文件末尾(常用于查看日志)
tail -f app.log

8.2 搜索文件内容

# 在文件中搜索关键词
grep "error" log.txt
Select-String "error" log.txt    # PowerShell

# 递归搜索目录中所有文件
grep -r "TODO" src/
Select-String -Recurse "TODO" src/   # PowerShell

# 搜索文件名
find . -name "*.py"
Get-ChildItem -Recurse -Filter "*.py"   # PowerShell

8.3 文件信息

# 查看文件大小和磁盘使用
du -sh folder/                       # Linux/macOS
du -h --max-depth=1                  # 查看一级子目录大小

# 查看磁盘总空间
df -h                                # Linux/macOS
Get-PSDrive C                        # PowerShell

九、进程管理

9.1 查看运行中的进程

# Linux / macOS
ps aux                  # 查看所有进程
ps aux | grep python    # 筛选 Python 相关进程
top                     # 实时进程监控(按 q 退出)

# Windows
tasklist
tasklist | findstr python

# PowerShell
Get-Process
Get-Process | Where-Object {$_.Name -like "*python*"}

9.2 终止进程

# Linux / macOS
kill 12345               # PID 为进程 ID
kill -9 12345             # 强制终止
pkill -f "python app.py"  # 按名称终止

# Windows
taskkill /PID 12345 /F

# PowerShell
Stop-Process -Id 12345 -Force
Stop-Process -Name python -Force
快速终止前台进程Ctrl + C 可立即终止当前正在前台运行的命令。这是最常用的中断方式。

十、管道与重定向

管道和重定向是 CLI 的核心能力,允许将命令的输出作为另一个命令的输入,或将输出写入文件

10.1 管道 |

将左边命令的输出传给右边命令处理:

# 统计目录下 Python 文件数量
ls | grep ".py" | wc -l

# 查找占用 8080 端口的进程
netstat -ano | findstr :8080

# 将长输出分页显示
ps aux | less

# PowerShell 管道示例
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

10.2 重定向

# > 覆盖写入文件
echo "log message" > output.log

# >> 追加写入文件
echo "another line" >> output.log

# 2> 重定向错误输出
python script.py 2> error.log

# &> 同时重定向标准输出和错误
python script.py &> all_output.log

10.3 实用组合

# 将 pip 安装日志保存到文件
pip install numpy > install.log 2>&1

# 统计代码行数
find . -name "*.py" | xargs wc -l | tail -1

# 快速创建多文件备份
cp *.py backup/

十一、环境变量

环境变量是操作系统层面的全局配置,影响所有程序的运行行为。

11.1 查看环境变量

# Linux / macOS
echo $PATH
echo $HOME

# Windows (cmd)
echo %PATH%

# PowerShell
echo $env:PATH
echo $env:USERPROFILE

11.2 设置环境变量

# 临时设置(仅当前终端会话有效)
export API_KEY="abc123"             # Linux/macOS
$env:API_KEY = "abc123"             # PowerShell
set API_KEY=abc123                  # Windows cmd

# 永久设置(写入配置文件)
# Linux/macOS: 添加到 ~/.bashrc 或 ~/.zshrc
echo 'export API_KEY="abc123"' >> ~/.bashrc

# Windows: 系统属性 → 高级 → 环境变量,或使用 PowerShell
[Environment]::SetEnvironmentVariable("API_KEY", "abc123", "User")

11.3 PATH 变量

PATH 是最重要的环境变量 它告诉操作系统去哪些目录查找可执行程序。当在终端输入 python 时,系统会按 PATH 中列出的目录顺序依次查找 python.exe。若报错”命令未找到”,通常是该程序未安装或未加入 PATH。

十二、包管理器

包管理器是 CLI 中最常用的工具类别之一,用于安装、升级、卸载软件。

管理器用途平台常用命令
pipPython 包跨平台pip install / uninstall / list
npmNode.js 包跨平台npm install / init / run
condaPython + 科学计算跨平台conda install / create / activate
wingetWindows 软件Windowswinget install / search / upgrade
brewmacOS 软件macOSbrew install / search / update
aptLinux (Debian) 软件Linuxapt install / search / update
git版本控制跨平台git clone / pull / push / add / commit

pip 快速参考

pip install package_name         # 安装包
pip install -r requirements.txt   # 从文件批量安装
pip install -e .                  # 可编辑模式安装本地项目
pip uninstall package_name       # 卸载包
pip list                          # 查看已安装包
pip show package_name             # 查看包详细信息
pip install --upgrade package    # 升级包
pip freeze > requirements.txt     # 导出当前环境依赖

十三、常用开发命令

######## Python 开发 ########
python --version                 # 查看 Python 版本
python -m venv venv               # 创建虚拟环境
venv\Scripts\activate             # 激活虚拟环境 (Windows)
source venv/bin/activate          # 激活虚拟环境 (macOS/Linux)
python main.py                    # 运行 Python 脚本
python -m pytest tests/           # 运行测试
jupyter notebook                  # 启动 Jupyter

######## Git 版本控制 ########
git clone https://github.com/xxx/project.git   # 克隆项目
git status                                   # 查看状态
git add .                                    # 暂存所有修改
git commit -m "描述信息"                       # 提交
git push origin main                         # 推送
git pull origin main                         # 拉取更新
git log --oneline                            # 查看提交历史
git branch feature-xxx                        # 创建分支
git checkout feature-xxx                      # 切换分支

######## Node.js 开发 ########
node --version                    # 查看 Node 版本
npm init -y                       # 初始化项目
npm install express               # 安装依赖
npm run dev                       # 运行脚本

######## Docker ########
docker ps                         # 查看运行中的容器
docker run -it ubuntu bash        # 启动容器
docker build -t myapp .           # 构建镜像

十四、进阶技巧

14.1 命令历史

# 查看历史命令
history                              # Linux/macOS
history | Select-String "git"        # PowerShell 搜索历史

# 快捷键
↑ / ↓                                # 上下翻历史命令
Ctrl + R                             # 搜索历史命令(反向搜索)
!!                                   # 重复上一条命令
!$                                   # 上一条命令的最后一个参数

14.2 Tab 自动补全

输入命令或路径的前几个字符后,按 Tab 键自动补全:

# 输入部分命令后按 Tab
pyth[TAB]        # → python
cd doc[TAB]      # → cd Documents/
pip ins[TAB]     # → pip install
养成习惯 频繁使用 Tab 补全可以大幅减少打字量并避免拼写错误。几乎所有现代 Shell 都支持此功能。

14.3 快捷键速查

快捷键功能
Ctrl + C中断当前命令
Ctrl + Z挂起当前进程(Linux/macOS)/ 撤销输入(Windows)
Ctrl + L清屏(等价于 clear
Ctrl + A光标跳到行首
Ctrl + E光标跳到行尾
Ctrl + W删除光标前的一个单词
Ctrl + U删除从行首到光标的所有内容
Ctrl + K删除从光标到行尾的所有内容
Ctrl + R反向搜索历史命令

14.4 通配符

# * 匹配任意字符
ls *.py                  # 列出所有 .py 文件
rm *.log                  # 删除所有 .log 文件

# ? 匹配单个字符
ls file?.txt              # 匹配 file1.txt, fileA.txt 等

14.5 编写 Shell 脚本

将常用命令组合写入脚本文件,一键执行:

#!/bin/bash
# deploy.sh — 一键部署脚本

echo "=== 更新代码 ==="
git pull origin main

echo "=== 安装依赖 ==="
pip install -r requirements.txt

echo "=== 运行测试 ==="
python -m pytest tests/ -v

echo "=== 部署完成 ==="
$bash deploy.sh

十五、命令速查表

用途Linux/macOSWindows (cmd)PowerShell
当前路径pwdcdGet-Location
列目录ls -ladirGet-ChildItem
切目录cd pathcd pathSet-Location path
建目录mkdir -p pathmkdir pathNew-Item -ItemType Dir
复制cp src dstcopy src dstCopy-Item src dst
移动mv src dstmove src dstMove-Item src dst
删除文件rm filedel fileRemove-Item file
删目录rm -rf dirrmdir /s /q dirRemove-Item -Recurse dir
看文件cat filetype fileGet-Content file
搜内容grep "x" filefindstr "x" fileSelect-String "x" file
看进程ps auxtasklistGet-Process
杀进程kill PIDtaskkill /PID n /FStop-Process -Id n
清屏clearclsClear-Host
帮助man commandcommand /?Get-Help command

核心要点总结

CLI 本质
通过文本命令与计算机交互,核心优势是精确、高效、可脚本化
命令结构
命令 [选项] [参数],忘就用 --help
导航
pwd 看位置、ls 看内容、cd 切目录
文件操作
mkdir 建、cp 复制、mv 移动、rm 删除(慎用)
效率技巧
Tab 补全、方向键翻历史、Ctrl+C 中断、Ctrl+R 搜索历史
进阶能力
管道 | 连接命令、重定向 >> 写文件、环境变量配置
学习路径
先掌握导航+文件操作 → 再学常用工具(git/pip/npm)→ 最后练脚本自动化

1. What is CLI

CLI (Command Line Interface) is a way of interacting with a computer through plain-text commands. Unlike using a mouse to click on graphical interfaces (GUI), CLI requires users to type text commands in a terminal, and the computer returns text results after execution.

Core Components

ComponentDescriptionExamples
TerminalA window program that receives and displays textWindows Terminal, iTerm2
ShellA program that interprets and executes commandsPowerShell, bash, zsh
CommandTells the computer what operation to performcd, ls, git
ArgumentThe target object the command operates onFile name, path, URL
Option (Flag)Switches that modify command behavior-h, --help, -f

Historical Background

In the 1960s-1980s, CLI was the only way to interact with computers. After graphical interfaces (GUI) became widespread, CLI gradually moved behind the scenes, but it remains indispensable in the following areas:

  • Software Development — Code compilation, testing, version control, dependency management
  • Server Administration — Remote management of headless servers
  • Data Science — Python virtual environments, pip package management, Jupyter startup
  • DevOps / CI/CD — Automated deployment scripts, Docker operations

2. CLI vs GUI

DimensionCLI (Command Line)GUI (Graphical Interface)
InteractionKeyboard text command inputMouse click, drag-and-drop
Learning CurveSteep, requires memorizing commandsGentle, WYSIWYG
EfficiencyExtremely fast once proficient (batch/automation)Suitable for simple, occasional tasks
ReproducibilityCommands can be written into scripts for automatic executionDifficult to precisely replicate steps
Resource UsageMinimal, no graphical rendering overheadHigher
Remote OperationsNative SSH supportRequires Remote Desktop / VNC
PrecisionCompletely precise, unambiguousDepends on UI design
Key Takeaway CLI and GUI are not opposing approaches. GUI is suited for exploration and daily use, while CLI excels at precise control and automation. Professional developers typically use both.

3. Common CLI Programs (Shells)

A Shell is a “command interpreter” that reads user-input commands and passes them to the operating system for execution. Different operating systems provide different Shells:

ShellPlatformFeaturesPrompt Example
cmd.exeWindowsTraditional Windows command line, basic functionalityC:\Users\xxx>
PowerShellWindows macOS LinuxMicrosoft’s modern Shell, supports pipelines, objects, scriptingPS C:\Users\xxx>
bashmacOS LinuxMost universal Unix Shell, default on almost all serversuser@host:~$
zshmacOSDefault Shell since macOS Catalina, rich plugin ecosystem (Oh My Zsh)user@mac ~ %
fishCross-platformFriendly auto-completion and syntax highlightinguser@host ~>

Recommendations for Windows Users

Windows offers three commonly used terminals:

cmd.exe

The most basic option, compatible with legacy scripts. Does not support modern features (such as pipeline objects, aliases). Not recommended as the daily driver.

PowerShell (Recommended)

Powerful, supports Unix-style commands like ls and cd, native JSON/XML processing. The top choice for Windows development.

WSL / Git Bash

Run a Linux environment within Windows. Ideal for scenarios that require Linux commands (such as shell scripts, Docker).

Windows Terminal

Microsoft’s official terminal app, supports multi-tab, custom themes. Can run cmd / PowerShell / WSL simultaneously.

4. How to Open CLI

PlatformMethodDescription
WindowsWin + R → type powershell → EnterQuick open PowerShell
WindowsRight-click Start menu → “Windows Terminal” or “Terminal”Open multi-tab terminal
WindowsType powershell in File Explorer address barOpen terminal in current directory
WindowsRight-click folder → “Open in Terminal”Native in Windows 11
macOSCmd + Space → search “Terminal”Open Terminal (zsh)
macOSFinder → Applications → Utilities → TerminalManual navigation
LinuxCtrl + Alt + TShortcut on most distributions
First Thing After Opening Enter the following command to verify your Shell type:
$echo $SHELL
Or in PowerShell:
PS>$PSVersionTable

5. Basic Command Structure

Every CLI command follows a unified syntax format:

$command [options] [arguments]

Meaning of each part:

PartPurposeExamples
CommandThe program or operation to executegit, python, pip, npm
Option (short)Starts with a single -, controls behavior-h, -v, -f
Option (long)Starts with double --, more explicit meaning--help, --version
ArgumentThe target object the command operates onFile name, path, URL, text

Practical Breakdown Example

$pip install –upgrade numpy
PartContentMeaning
CommandpipPython package manager
Sub-commandinstallPerform installation
Option--upgradeUpgrade installed package to latest version
ArgumentnumpyName of the package to install/upgrade

More Examples

# View help (supported by almost all CLI tools)
git --help
python --help
pip --help

# View version
python --version
node --version

# Multiple short options can be combined
ls -a -l -h     # equivalent to
ls -alh

# Long and short options are equivalent
pip install -r requirements.txt
pip install --requirement requirements.txt
Lifesaver Tip When you forget how to use a command, type command --help or command -h at any time. This works for almost all CLI tools. For example, git --help, docker --help, pytest --help.

6. File System Navigation

The first step in CLI is learning to navigate the file system. The following commands work across all platforms (PowerShell also supports them):

6.1 Check Current Path

$pwd
/home/user/projects/my-app

6.2 List Directory Contents

$ls
file1.txt  folder_a  README.md  src/

Common options:

OptionMeaningWindows (cmd) Equivalent
ls -lDetailed listing (permissions, size, time)dir
ls -aShow hidden files (files starting with .)dir /a
ls -laDetailed listing + hidden filesdir /a
ls -lhHuman-readable file sizes (KB/MB)

6.3 Change Directory

$cd /home/user/projects
# Enter subdirectory
cd src

# Go up one level
cd ..

# Go up two levels
cd ../..

# Return to home directory
cd ~          # Linux/macOS
cd %USERPROFILE%    # Windows (cmd)
cd $HOME     # PowerShell

# Return to previous directory
cd -
Windows Path Notation Windows uses backslashes \ (e.g., C:\Users\xxx), but PowerShell and modern tools also support forward slashes / (e.g., C:/Users/xxx). It is recommended to use forward slashes consistently for cross-platform compatibility.

7. File & Directory Operations

7.1 Create Directories

# Linux / macOS / PowerShell
mkdir new_folder

# Create nested directories (auto-create parent directories if they don't exist)
mkdir -p project/src/utils     # Linux/macOS
New-Item -ItemType Directory -Force -Path project/src/utils  # PowerShell

7.2 Create / Write Files

# Create empty file with touch (works on Linux/macOS/PowerShell)
touch config.json

# Write content with echo (> overwrite, >> append)
echo "Hello" > hello.txt
echo "World" >> hello.txt

7.3 Copy Files / Directories

# Linux / macOS
cp file1.txt file2.txt          # Copy file
cp -r folder_a folder_b          # Recursively copy directory

# Windows (cmd)
copy file1.txt file2.txt
xcopy folder_a folder_b /E /I

# PowerShell
Copy-Item file1.txt file2.txt
Copy-Item -Recurse folder_a folder_b

7.4 Move / Rename

# Linux / macOS
mv old_name.txt new_name.txt     # Rename
mv file.txt folder/              # Move to directory

# Windows (cmd)
move old_name.txt new_name.txt

# PowerShell
Move-Item old_name.txt new_name.txt
Move-Item file.txt folder/

7.5 Delete Files / Directories

Warning There is no “Recycle Bin” mechanism in CLI. Files deleted with rm / del cannot be recovered. Always operate with caution, especially with rm -rf.
# Linux / macOS
rm file.txt                      # Delete file
rm -r folder/                    # Recursively delete directory and contents
rm -rf folder/                   # Force recursive delete (no confirmation)

# Windows (cmd)
del file.txt
rmdir /s /q folder

# PowerShell
Remove-Item file.txt
Remove-Item -Recurse -Force folder

8. File Viewing & Editing

8.1 View File Contents

# View entire content (small files)
cat file.txt      # Linux/macOS/PowerShell
type file.txt     # Windows cmd
Get-Content file.txt  # PowerShell full syntax

# Paginated view (large files)
less file.txt     # Linux/macOS, press q to exit
more file.txt     # Windows cmd

# View first N lines
head -20 file.txt
Get-Content file.txt -Head 20   # PowerShell

# View last N lines
tail -20 file.txt
Get-Content file.txt -Tail 20   # PowerShell

# Real-time tail (commonly used for log viewing)
tail -f app.log

8.2 Search File Contents

# Search for a keyword in a file
grep "error" log.txt
Select-String "error" log.txt    # PowerShell

# Recursively search all files in a directory
grep -r "TODO" src/
Select-String -Recurse "TODO" src/   # PowerShell

# Search by filename
find . -name "*.py"
Get-ChildItem -Recurse -Filter "*.py"   # PowerShell

8.3 File Information

# Check file sizes and disk usage
du -sh folder/                       # Linux/macOS
du -h --max-depth=1                  # View first-level subdirectory sizes

# Check total disk space
df -h                                # Linux/macOS
Get-PSDrive C                        # PowerShell

9. Process Management

9.1 View Running Processes

# Linux / macOS
ps aux                  # View all processes
ps aux | grep python    # Filter Python-related processes
top                     # Real-time process monitoring (press q to exit)

# Windows
tasklist
tasklist | findstr python

# PowerShell
Get-Process
Get-Process | Where-Object {$_.Name -like "*python*"}

9.2 Terminate Processes

# Linux / macOS
kill 12345               # PID is the process ID
kill -9 12345             # Force terminate
pkill -f "python app.py"  # Terminate by name

# Windows
taskkill /PID 12345 /F

# PowerShell
Stop-Process -Id 12345 -Force
Stop-Process -Name python -Force
Quickly Terminate Foreground Process Press Ctrl + C to immediately terminate the currently running foreground command. This is the most commonly used interruption method.

10. Pipes & Redirection

Pipes and redirection are core CLI capabilities that allow the output of one command to be used as input for another, or to write output to files.

10.1 Pipes |

Pass the output of the left command to the right command for processing:

# Count Python files in a directory
ls | grep ".py" | wc -l

# Find the process using port 8080
netstat -ano | findstr :8080

# Paginate long output
ps aux | less

# PowerShell pipe example
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5

10.2 Redirection

# > Overwrite to file
echo "log message" > output.log

# >> Append to file
echo "another line" >> output.log

# 2> Redirect error output
python script.py 2> error.log

# &> Redirect both stdout and stderr
python script.py &> all_output.log

10.3 Practical Combinations

# Save pip install log to file
pip install numpy > install.log 2>&1

# Count lines of code
find . -name "*.py" | xargs wc -l | tail -1

# Quick backup of multiple files
cp *.py backup/

11. Environment Variables

Environment variables are global configurations at the operating system level that affect the runtime behavior of all programs.

11.1 View Environment Variables

# Linux / macOS
echo $PATH
echo $HOME

# Windows (cmd)
echo %PATH%

# PowerShell
echo $env:PATH
echo $env:USERPROFILE

11.2 Set Environment Variables

# Temporary setting (only valid for current terminal session)
export API_KEY="abc123"             # Linux/macOS
$env:API_KEY = "abc123"             # PowerShell
set API_KEY=abc123                  # Windows cmd

# Permanent setting (write to config file)
# Linux/macOS: add to ~/.bashrc or ~/.zshrc
echo 'export API_KEY="abc123"' >> ~/.bashrc

# Windows: System Properties → Advanced → Environment Variables, or use PowerShell
[Environment]::SetEnvironmentVariable("API_KEY", "abc123", "User")

11.3 The PATH Variable

PATH is the Most Important Environment Variable It tells the operating system which directories to search for executable programs. When you type python in the terminal, the system searches for python.exe in the directories listed in PATH in order. If you get a “command not found” error, the program is usually not installed or not added to PATH.

12. Package Managers

Package managers are one of the most commonly used tool categories in CLI, used for installing, upgrading, and uninstalling software.

ManagerPurposePlatformCommon Commands
pipPython packagesCross-platformpip install / uninstall / list
npmNode.js packagesCross-platformnpm install / init / run
condaPython + scientific computingCross-platformconda install / create / activate
wingetWindows softwareWindowswinget install / search / upgrade
brewmacOS softwaremacOSbrew install / search / update
aptLinux (Debian) softwareLinuxapt install / search / update
gitVersion controlCross-platformgit clone / pull / push / add / commit

pip Quick Reference

pip install package_name         # Install package
pip install -r requirements.txt   # Batch install from file
pip install -e .                  # Install local project in editable mode
pip uninstall package_name       # Uninstall package
pip list                          # View installed packages
pip show package_name             # View package details
pip install --upgrade package    # Upgrade package
pip freeze > requirements.txt     # Export current environment dependencies

13. Common Development Commands

######## Python Development ########
python --version                 # Check Python version
python -m venv venv               # Create virtual environment
venv\Scripts\activate             # Activate virtual environment (Windows)
source venv/bin/activate          # Activate virtual environment (macOS/Linux)
python main.py                    # Run Python script
python -m pytest tests/           # Run tests
jupyter notebook                  # Start Jupyter

######## Git Version Control ########
git clone https://github.com/xxx/project.git   # Clone project
git status                                   # Check status
git add .                                    # Stage all changes
git commit -m "commit message"               # Commit
git push origin main                         # Push
git pull origin main                         # Pull updates
git log --oneline                            # View commit history
git branch feature-xxx                        # Create branch
git checkout feature-xxx                      # Switch branch

######## Node.js Development ########
node --version                    # Check Node version
npm init -y                       # Initialize project
npm install express               # Install dependency
npm run dev                       # Run script

######## Docker ########
docker ps                         # View running containers
docker run -it ubuntu bash        # Start container
docker build -t myapp .           # Build image

14. Advanced Tips

14.1 Command History

# View command history
history                              # Linux/macOS
history | Select-String "git"        # PowerShell search history

# Shortcuts
↑ / ↓                                # Navigate up/down through history
Ctrl + R                             # Reverse search command history
!!                                   # Repeat last command
!$                                   # Last argument of previous command

14.2 Tab Auto-Completion

After typing the first few characters of a command or path, press Tab to auto-complete:

# Type partial command then press Tab
pyth[TAB]        # → python
cd doc[TAB]      # → cd Documents/
pip ins[TAB]     # → pip install
Build the Habit Frequently using Tab completion significantly reduces typing and avoids spelling errors. Almost all modern Shells support this feature.

14.3 Keyboard Shortcuts Reference

ShortcutFunction
Ctrl + CInterrupt current command
Ctrl + ZSuspend current process (Linux/macOS) / Undo input (Windows)
Ctrl + LClear screen (equivalent to clear)
Ctrl + AMove cursor to beginning of line
Ctrl + EMove cursor to end of line
Ctrl + WDelete the word before the cursor
Ctrl + UDelete everything from line start to cursor
Ctrl + KDelete everything from cursor to end of line
Ctrl + RReverse search command history

14.4 Wildcards

# * matches any characters
ls *.py                  # List all .py files
rm *.log                  # Delete all .log files

# ? matches a single character
ls file?.txt              # Matches file1.txt, fileA.txt, etc.

14.5 Writing Shell Scripts

Combine frequently used commands into a script file for one-click execution:

#!/bin/bash
# deploy.sh — One-click deployment script

echo "=== Updating code ==="
git pull origin main

echo "=== Installing dependencies ==="
pip install -r requirements.txt

echo "=== Running tests ==="
python -m pytest tests/ -v

echo "=== Deployment complete ==="
$bash deploy.sh

15. Command Quick Reference

PurposeLinux/macOSWindows (cmd)PowerShell
Current pathpwdcdGet-Location
List directoryls -ladirGet-ChildItem
Change directorycd pathcd pathSet-Location path
Create directorymkdir -p pathmkdir pathNew-Item -ItemType Dir
Copycp src dstcopy src dstCopy-Item src dst
Movemv src dstmove src dstMove-Item src dst
Delete filerm filedel fileRemove-Item file
Delete directoryrm -rf dirrmdir /s /q dirRemove-Item -Recurse dir
View filecat filetype fileGet-Content file
Search contentgrep "x" filefindstr "x" fileSelect-String "x" file
View processesps auxtasklistGet-Process
Kill processkill PIDtaskkill /PID n /FStop-Process -Id n
Clear screenclearclsClear-Host
Helpman commandcommand /?Get-Help command

Key Takeaways Summary

CLI Essence
Interact with computers via text commands; core advantages are precision, efficiency, and scriptability
Command Structure
command [options] [arguments]; if you forget, use --help
Navigation
pwd to check location, ls to view contents, cd to change directory
File Operations
mkdir to create, cp to copy, mv to move, rm to delete (use with caution)
Efficiency Tips
Tab completion, arrow keys for history, Ctrl+C to interrupt, Ctrl+R to search history
Advanced Skills
Pipe | to chain commands, redirect >> to write files, environment variable configuration
Learning Path
Master navigation + file ops first → then learn common tools (git/pip/npm) → finally practice scripting automation

Based on Linux man pages, Microsoft PowerShell documentation, and Git official documentation