国际访客建议访问 Primers 编程伙伴 国际版站点 > Bash 教程 > chroot 以获得更好的体验。

# Bash 的 chroot 命令

chroot [OPTION] NEWROOT [COMMAND [ARG]...]

!subtitle:功能

执行命令时指定根路径。

!subtitle:类型

可执行文件(/usr/sbin/chroot),属于 coreutils

!subtitle:参数

  • OPTION 选项:

    • --groups=G_LIST - 以列表(g1,g2,...,gn)的格式补充组

    • --userspec=USER:GROUP - 指定用户和组

    • --skip-chdir - 不更改工作目录

    • --help - 显示帮助

    • --version - 显示版本

  • NEWROOT 要作为根路径的路径

  • COMMAND 要执行的命令;如果不指定此参数,则切换后运行当前 shell 程序

  • ARG 命令的参数列表

!subtitle:返回值

  • 125 - chroot 自身失败

  • 126 - COMMAND 无法运行

  • 127 - COMMAND 不存在

  • 其它情况返回 COMMAND 的返回值

# 示例

$ ls /tmp/                                          # 查看 /tmp 目录
tmp.XG4RL3jbgF  tmp.Urtrw97emL  tmp.M8ln2SXW4p
$ mkdir -p ./fake_root/tmp                          # 创建目录
$ touch ./fake_root/tmp/1.txt                       # 创建文件
$ wget https://busybox.net/downloads/binaries/1.35.0-x86_64-linux-musl/busybox -O ./fake_root/busybox
$ sudo chroot ./fake_root/ ./busybox ls /tmp/       # 指定 ./fake_root/ 为根目录,查看 /tmp 目录
1.txt

因为将根目录设为 ./fake_root/ 之后,没有 /bin 目录下的各种命令,因此下载了 busybox 来执行 ls 命令。

# 推荐阅读

# 手册

CHROOT(8)                        User Commands                       CHROOT(8)

NAME
       chroot - run command or interactive shell with special root directory

SYNOPSIS
       chroot [OPTION] NEWROOT [COMMAND [ARG]...]
       chroot OPTION

DESCRIPTION
       Run COMMAND with root directory set to NEWROOT.

       --groups=G_LIST
              specify supplementary groups as g1,g2,..,gN

       --userspec=USER:GROUP
              specify user and group (ID or name) to use

       --skip-chdir
              do not change working directory to '/'

       --help display this help and exit

       --version
              output version information and exit

       If no command is given, run '"$SHELL" -i' (default: '/bin/sh -i').

   Exit status:
       125    if the chroot command itself fails

       126    if COMMAND is found but cannot be invoked

       127    if COMMAND cannot be found

       -      the exit status of COMMAND otherwise

AUTHOR
       Written by Roland McGrath.

REPORTING BUGS
       GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
       Report any translation bugs to <https://translationproject.org/team/>

COPYRIGHT
       Copyright  ©  2023  Free Software Foundation, Inc.  License GPLv3+: GNU
       GPL version 3 or later <https://gnu.org/licenses/gpl.html>.
       This is free software: you are free  to  change  and  redistribute  it.
       There is NO WARRANTY, to the extent permitted by law.

SEE ALSO
       chroot(2)

       Full documentation <https://www.gnu.org/software/coreutils/chroot>
       or available locally via: info '(coreutils) chroot invocation'

GNU coreutils 9.4                 April 2024                         CHROOT(8)
本文 更新于: 2026-03-06 09:52:29 创建于: 2026-03-06 09:52:29