温馨提示×

能否用脚本配Debian Rust

小樊
35
2026-09-14 08:42:18
栏目: 编程语言

可以的,完全可以用脚本(Shell 脚本 / Ansible / Dockerfile 等)来在 Debian 上配置 Rust 环境。下面给你几种常见、实用、可脚本化的方式。


一、最推荐:用官方 rustup(可脚本化)

1️⃣ 纯 Shell 脚本方式

#!/usr/bin/env bash
set -e

# 安装依赖
sudo apt update
sudo apt install -y curl build-essential gcc

# 安装 Rust(非交互)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

# 载入环境变量
source "$HOME/.cargo/env"

# 验证
rustc --version
cargo --version

✅ 特点

  • 官方支持
  • 可升级:rustup update
  • CI / 服务器友好

二、在 Debian 上用 apt 安装(不推荐生产)

sudo apt update
sudo apt install -y rustc cargo

⚠️ 缺点

  • 版本通常偏旧
  • 不利于多版本管理

适合:只跑一次的小工具


三、Docker 方式(最干净)

FROM debian:12

RUN apt update && apt install -y curl build-essential

RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y

ENV PATH="/root/.cargo/bin:${PATH}"

CMD ["bash"]

构建:

docker build -t debian-rust .
docker run -it debian-rust rustc --version

✅ 适合:CI、隔离环境


四、Ansible 示例(自动化运维)

- name: Install Rust
  hosts: all
  tasks:
    - apt:
        name: [curl, build-essential]
        update_cache: yes

    - shell: |
        curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
      args:
        creates: ~/.cargo/bin/rustc

五、常见补充配置(可脚本)

# 换国内镜像(如中科大)
cat >> ~/.cargo/config.toml <<EOF
[source.crates-io]
replace-with = "ustc"

[source.ustc]
registry = "sparse+https://mirrors.ustc.edu.cn/crates.io-index/"
EOF

六、选择建议

场景 推荐方式
本地开发 rustup
服务器 rustup + 脚本
CI Docker
批量机器 Ansible + rustup

如果你愿意,可以告诉我:

  • Debian 版本(11 / 12?)
  • 是否用于 CI / 服务器 / 桌面
  • 是否需要 交叉编译 / WASM / 特定 Rust 版本

我可以直接帮你写一份完整可用脚本

0