命令行界面(CLI)详细说明文档
从概念解析到实际操作,全面理解什么是 CLI 以及如何高效使用命令行完成日常工作
一、什么是 CLI
CLI(Command Line Interface,命令行界面)是一种通过纯文本命令与计算机交互的方式。与使用鼠标点击图形界面(GUI)不同,CLI 要求用户在终端中输入文字指令,计算机执行后返回文本结果。
核心组成要素
| 要素 | 说明 | 示例 |
|---|---|---|
| 终端 / Terminal | 接收和显示文本的窗口程序 | Windows Terminal、iTerm2 |
| Shell | 解释和执行命令的程序 | PowerShell、bash、zsh |
| 命令 / Command | 告诉计算机执行什么操作 | cd、ls、git |
| 参数 / 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 程序(Shell)
Shell 是”命令解释器”,负责读取用户输入的命令并交给操作系统执行。不同操作系统提供不同的 Shell:
| Shell | 平台 | 特点 | 提示符示例 |
|---|---|---|---|
| cmd.exe | Windows | Windows 传统命令行,功能基础 | C:\Users\xxx> |
| PowerShell | Windows macOS Linux | 微软现代 Shell,支持管道、对象、脚本 | PS C:\Users\xxx> |
| bash | macOS Linux | 最通用的 Unix Shell,几乎所有服务器默认 | user@host:~$ |
| zsh | macOS | macOS Catalina 起默认 Shell,插件生态丰富(Oh My Zsh) | user@mac ~ % |
| fish | 跨平台 | 友好的自动补全和语法高亮 | user@host ~> |
Windows 用户的选择建议
Windows 提供三种常用终端:
最基础,兼容老旧脚本。不支持现代特性(如管道对象、别名),不推荐作为日常主力。
功能强大,支持 ls、cd 等 Unix 风格命令,原生处理 JSON/XML,Windows 开发首选。
在 Windows 中运行 Linux 环境。适合需要 Linux 命令的场景(如 shell 脚本、Docker)。
微软官方终端应用,支持多标签、自定义主题。可同时运行 cmd / PowerShell / WSL。
四、如何打开 CLI
| 平台 | 方式 | 说明 |
|---|---|---|
| Windows | Win + R → 输入 powershell → 回车 | 快速打开 PowerShell |
| Windows | 右键开始菜单 → “Windows Terminal” 或 “终端” | 打开多标签终端 |
| Windows | 在文件资源管理器地址栏输入 powershell | 在当前目录打开终端 |
| Windows | 右键文件夹 → “在终端中打开” | Win11 原生支持 |
| macOS | Cmd + 空格 → 搜索 “Terminal” | 打开终端(zsh) |
| macOS | Finder → 应用程序 → 实用工具 → 终端 | 手动导航 |
| Linux | Ctrl + Alt + T | 大多数发行版的快捷键 |
五、命令的基本结构
每一条 CLI 命令都遵循统一的语法格式:
各部分的含义:
| 部分 | 作用 | 示例 |
|---|---|---|
| 命令 | 要执行的程序或操作 | git、python、pip、npm |
| 选项(短格式) | 以单个 - 开头,控制行为 | -h、-v、-f |
| 选项(长格式) | 以双 -- 开头,含义更明确 | --help、--version |
| 参数 | 命令操作的对象 | 文件名、路径、URL、文本 |
实际拆解示例
| 部分 | 内容 | 含义 |
|---|---|---|
| 命令 | pip | Python 包管理工具 |
| 子命令 | 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 --help、docker --help、pytest --help。
六、文件系统导航
CLI 操作的第一步是学会在文件系统中移动。以下命令在所有平台通用(PowerShell 同样支持):
6.1 查看当前路径
/home/user/projects/my-app
6.2 列出目录内容
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 src
# 返回上一级目录
cd ..
# 返回上两级
cd ../..
# 回到用户主目录
cd ~ # Linux/macOS
cd %USERPROFILE% # Windows (cmd)
cd $HOME # PowerShell
# 回到上一次所在的目录
cd -
\(如 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 删除文件 / 目录
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 变量
python 时,系统会按 PATH 中列出的目录顺序依次查找 python.exe。若报错”命令未找到”,通常是该程序未安装或未加入 PATH。
十二、包管理器
包管理器是 CLI 中最常用的工具类别之一,用于安装、升级、卸载软件。
| 管理器 | 用途 | 平台 | 常用命令 |
|---|---|---|---|
pip | Python 包 | 跨平台 | pip install / uninstall / list |
npm | Node.js 包 | 跨平台 | npm install / init / run |
conda | Python + 科学计算 | 跨平台 | conda install / create / activate |
winget | Windows 软件 | Windows | winget install / search / upgrade |
brew | macOS 软件 | macOS | brew install / search / update |
apt | Linux (Debian) 软件 | Linux | apt 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
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 "=== 部署完成 ==="
十五、命令速查表
| 用途 | Linux/macOS | Windows (cmd) | PowerShell |
|---|---|---|---|
| 当前路径 | pwd | cd | Get-Location |
| 列目录 | ls -la | dir | Get-ChildItem |
| 切目录 | cd path | cd path | Set-Location path |
| 建目录 | mkdir -p path | mkdir path | New-Item -ItemType Dir |
| 复制 | cp src dst | copy src dst | Copy-Item src dst |
| 移动 | mv src dst | move src dst | Move-Item src dst |
| 删除文件 | rm file | del file | Remove-Item file |
| 删目录 | rm -rf dir | rmdir /s /q dir | Remove-Item -Recurse dir |
| 看文件 | cat file | type file | Get-Content file |
| 搜内容 | grep "x" file | findstr "x" file | Select-String "x" file |
| 看进程 | ps aux | tasklist | Get-Process |
| 杀进程 | kill PID | taskkill /PID n /F | Stop-Process -Id n |
| 清屏 | clear | cls | Clear-Host |
| 帮助 | man command | command /? | Get-Help command |
核心要点总结
命令 [选项] [参数],忘就用 --helppwd 看位置、ls 看内容、cd 切目录mkdir 建、cp 复制、mv 移动、rm 删除(慎用)Ctrl+C 中断、Ctrl+R 搜索历史| 连接命令、重定向 >> 写文件、环境变量配置Command Line Interface (CLI) Detailed Guide
From concepts to hands-on practice, a comprehensive understanding of what CLI is and how to use the command line efficiently in daily work
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
| Component | Description | Examples |
|---|---|---|
| Terminal | A window program that receives and displays text | Windows Terminal, iTerm2 |
| Shell | A program that interprets and executes commands | PowerShell, bash, zsh |
| Command | Tells the computer what operation to perform | cd, ls, git |
| Argument | The target object the command operates on | File 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
| Dimension | CLI (Command Line) | GUI (Graphical Interface) |
|---|---|---|
| Interaction | Keyboard text command input | Mouse click, drag-and-drop |
| Learning Curve | Steep, requires memorizing commands | Gentle, WYSIWYG |
| Efficiency | Extremely fast once proficient (batch/automation) | Suitable for simple, occasional tasks |
| Reproducibility | Commands can be written into scripts for automatic execution | Difficult to precisely replicate steps |
| Resource Usage | Minimal, no graphical rendering overhead | Higher |
| Remote Operations | Native SSH support | Requires Remote Desktop / VNC |
| Precision | Completely precise, unambiguous | Depends on UI design |
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:
| Shell | Platform | Features | Prompt Example |
|---|---|---|---|
| cmd.exe | Windows | Traditional Windows command line, basic functionality | C:\Users\xxx> |
| PowerShell | Windows macOS Linux | Microsoft’s modern Shell, supports pipelines, objects, scripting | PS C:\Users\xxx> |
| bash | macOS Linux | Most universal Unix Shell, default on almost all servers | user@host:~$ |
| zsh | macOS | Default Shell since macOS Catalina, rich plugin ecosystem (Oh My Zsh) | user@mac ~ % |
| fish | Cross-platform | Friendly auto-completion and syntax highlighting | user@host ~> |
Recommendations for Windows Users
Windows offers three commonly used terminals:
The most basic option, compatible with legacy scripts. Does not support modern features (such as pipeline objects, aliases). Not recommended as the daily driver.
Powerful, supports Unix-style commands like ls and cd, native JSON/XML processing. The top choice for Windows development.
Run a Linux environment within Windows. Ideal for scenarios that require Linux commands (such as shell scripts, Docker).
Microsoft’s official terminal app, supports multi-tab, custom themes. Can run cmd / PowerShell / WSL simultaneously.
4. How to Open CLI
| Platform | Method | Description |
|---|---|---|
| Windows | Win + R → type powershell → Enter | Quick open PowerShell |
| Windows | Right-click Start menu → “Windows Terminal” or “Terminal” | Open multi-tab terminal |
| Windows | Type powershell in File Explorer address bar | Open terminal in current directory |
| Windows | Right-click folder → “Open in Terminal” | Native in Windows 11 |
| macOS | Cmd + Space → search “Terminal” | Open Terminal (zsh) |
| macOS | Finder → Applications → Utilities → Terminal | Manual navigation |
| Linux | Ctrl + Alt + T | Shortcut on most distributions |
5. Basic Command Structure
Every CLI command follows a unified syntax format:
Meaning of each part:
| Part | Purpose | Examples |
|---|---|---|
| Command | The program or operation to execute | git, python, pip, npm |
| Option (short) | Starts with a single -, controls behavior | -h, -v, -f |
| Option (long) | Starts with double --, more explicit meaning | --help, --version |
| Argument | The target object the command operates on | File name, path, URL, text |
Practical Breakdown Example
| Part | Content | Meaning |
|---|---|---|
| Command | pip | Python package manager |
| Sub-command | install | Perform installation |
| Option | --upgrade | Upgrade installed package to latest version |
| Argument | numpy | Name 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
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
/home/user/projects/my-app
6.2 List Directory Contents
file1.txt folder_a README.md src/
Common options:
| Option | Meaning | Windows (cmd) Equivalent |
|---|---|---|
ls -l | Detailed listing (permissions, size, time) | dir |
ls -a | Show hidden files (files starting with .) | dir /a |
ls -la | Detailed listing + hidden files | dir /a |
ls -lh | Human-readable file sizes (KB/MB) | — |
6.3 Change Directory
# 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 -
\ (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
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
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
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.
| Manager | Purpose | Platform | Common Commands |
|---|---|---|---|
pip | Python packages | Cross-platform | pip install / uninstall / list |
npm | Node.js packages | Cross-platform | npm install / init / run |
conda | Python + scientific computing | Cross-platform | conda install / create / activate |
winget | Windows software | Windows | winget install / search / upgrade |
brew | macOS software | macOS | brew install / search / update |
apt | Linux (Debian) software | Linux | apt install / search / update |
git | Version control | Cross-platform | git 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
14.3 Keyboard Shortcuts Reference
| Shortcut | Function |
|---|---|
Ctrl + C | Interrupt current command |
Ctrl + Z | Suspend current process (Linux/macOS) / Undo input (Windows) |
Ctrl + L | Clear screen (equivalent to clear) |
Ctrl + A | Move cursor to beginning of line |
Ctrl + E | Move cursor to end of line |
Ctrl + W | Delete the word before the cursor |
Ctrl + U | Delete everything from line start to cursor |
Ctrl + K | Delete everything from cursor to end of line |
Ctrl + R | Reverse 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 ==="
15. Command Quick Reference
| Purpose | Linux/macOS | Windows (cmd) | PowerShell |
|---|---|---|---|
| Current path | pwd | cd | Get-Location |
| List directory | ls -la | dir | Get-ChildItem |
| Change directory | cd path | cd path | Set-Location path |
| Create directory | mkdir -p path | mkdir path | New-Item -ItemType Dir |
| Copy | cp src dst | copy src dst | Copy-Item src dst |
| Move | mv src dst | move src dst | Move-Item src dst |
| Delete file | rm file | del file | Remove-Item file |
| Delete directory | rm -rf dir | rmdir /s /q dir | Remove-Item -Recurse dir |
| View file | cat file | type file | Get-Content file |
| Search content | grep "x" file | findstr "x" file | Select-String "x" file |
| View processes | ps aux | tasklist | Get-Process |
| Kill process | kill PID | taskkill /PID n /F | Stop-Process -Id n |
| Clear screen | clear | cls | Clear-Host |
| Help | man command | command /? | Get-Help command |
Key Takeaways Summary
command [options] [arguments]; if you forget, use --helppwd to check location, ls to view contents, cd to change directorymkdir to create, cp to copy, mv to move, rm to delete (use with caution)Ctrl+C to interrupt, Ctrl+R to search history| to chain commands, redirect >> to write files, environment variable configuration