(UNIX) Shell: 一门编程语言

(UNIX) Shell: 一门编程语言

2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

“多任务” 不是人机交互的全部

center

Windows 3.2 (1992): “多窗口管理器” 并不那么好用
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

The Shell Programming Language

UNIX 的用户可都是 hackers!

  • UNIX Shell: 基于文本替换的极简编程语言
    • 只有一种类型:字符串
    • 算术运算?对不起,我们不支持 😂 (但可以 expr 1 + 2)

语言机制

  • 预处理: $(), <()
  • 重定向: cmd > file < file 2> /dev/null
  • 顺序结构: cmd1; cmd2, cmd1 && cmd2, cmd1 || cmd2
  • 管道: cmd1 | cmd2
    • 这些命令被翻译成系统调用序列 (open, dup, pipe, fork, execve, waitpid, ...)
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

例子:实现重定向

利用子进程继承文件描述符的特性

  • 在父进程打开好文件,到子进程里腾挪
    • 发现还是 Windows API 更 “优雅”
int fd_in  = open(..., O_RDONLY | O_CLOEXEC);
int fd_out = open(..., O_WRONLY | O_CLOEXEC);

int pid = fork();
if (pid == 0) {
    dup2(fd_in, 0);
    dup2(fd_out, 1);
    execve(...);
} else {
    close(fd_in);
    close(fd_out);
    waitpid(pid, &status, 0);
}
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

读一读手册 (为数不多还值得读的手册)

man sh: dash — command interpreter (shell)

  • dash is the standard command interpreter for the system. The current version of dash is in the process of being changed to conform with the POSIX 1003.2 and 1003.2a specifications for the shell.
  • The shell is a command that reads lines from either a file or the terminal, interprets them, and generally executes other commands. It is the program that is running when a user logs into the system (although a user can select a different shell with the chsh(1) command).
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

UNIX Shell: 优点

优点:高效、简介、精确

  • 一种 “自然编程语言”:一行命令,协同多个程序
    • make -nB | grep ...
    • 最适合 quick & dirty 的 hackers

AI 时代的 UNIX Philosophy

  • man tcsetpgrp | ag -q 帮我生成新手友好的教程
  • 出了问题还可以 fxxk
    • 带过一个同学毕设改进 fxxk (现在他已经在 DeepSeek 开源周发代码了); 再想改进的时候,ChatGPT 来了 😭
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

UNIX Shell: 有优点就有缺点

无奈的取舍

  • Shell 的设计被 “1970s 的算力、算法和工程能力” 束缚了
    • 后人只好将错就错 (PowerShell: 我好用,但没人用 😭)

例子:操作的 “优先级”?

  • ls > a.txt | cat
    • 我已经重定向给 a.txt 了,cat 是不是就收不到输入了?
  • bash/zsh 的行为是不同的
    • 所以脚本用 #!/bin/bash 甚至 #!/bin/sh 保持兼容
  • 文本数据 “责任自负”
    • 空格 = 灾难
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

另一个有趣的例子

center

$ echo hello > /etc/a.txt
bash: /etc/a.txt: Permission denied

$ sudo echo hello > /etc/a.txt
bash: /etc/a.txt: Permission denied
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

A Zero-dependency UNIX Shell

真正体现 “Shell 是 Kernel 之外的 壳”

  • 来自 xv6
  • 完全基于系统调用 API,零库函数依赖
    • -ffreestanding 编译、ld 链接

支持的功能

  • 重定向/管道 ls > a.txt, ls | wc -l
  • 后台执行 ls &
  • 命令组合 (echo a ; echo b) | wc -l
2025 南京大学《操作系统原理》
(UNIX) Shell: 一门编程语言

展望未来

去年留下的 Open question

  • Shell (CLI/GUI) 的未来是什么

今年有了一些想法

  • 是一个 “半结构化” 的 “编程语言”
    • project files | filter out generated files | zip them
    • make a slides of UNIX shell | play it
    • 我就可以退休啦 😄
2025 南京大学《操作系统原理》