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

# Bash 的 shuf 命令

shuf [OPTION]... [FILE]

!subtitle:功能

生成随机的排列组合。

!subtitle:类型

可执行文件(/usr/bin/shuf),属于 coreutils

!subtitle:参数

  • OPTION 选项:

    • -e, --echo - 将每个参数视为一行输入

    • -i, --input-range=LO-HI - 将数值 LOHI 随机排列

    • -n, --head-count=COUNT - 输出保留前 COUNT

    • -o, --output=FILE - 将结果输出到 FILE 文件;默认为标准输出

    • --random-source=FILE - 从 FILE 文件获取随机数

    • -r, --repeat - 输出可以重复

    • -z, --zero-terminated - 以空字符(\0)作为行的结尾,而不是换行符(\n

    • --help - 显示帮助

    • --version - 显示版本

  • FILE - 文件;如果没有这个参数或指定为 -,则读取标准输入

# 示例

!subtitle:生成随机数列表

$ shuf -i 1-5           # 将 1-5 随机排列
2
5
4
1
3
$ shuf -i 1-5 -r -n 10  # 生成 10 个 1-5 的随机数
3
5
2
1
5
4
1
5
3
2

!subtitle:将文件的行随机排列

$ echo -e "A\nB\nC\nD\nE" > 1.txt   # 创建文件
$ shuf 1.txt                        # 将文件的行随机打乱
D
A
C
E
B
$ echo -e "A\nB\nC\nD\nE" > 1.txt   # 创建文件
$ shuf -r -n 10 1.txt               # 将文件的行随机输出 10 次
D
A
C
E
B

# 推荐阅读

# 手册

SHUF(1)                          User Commands                         SHUF(1)

NAME
       shuf - generate random permutations

SYNOPSIS
       shuf [OPTION]... [FILE]
       shuf -e [OPTION]... [ARG]...
       shuf -i LO-HI [OPTION]...

DESCRIPTION
       Write a random permutation of the input lines to standard output.

       With no FILE, or when FILE is -, read standard input.

       Mandatory  arguments  to  long  options are mandatory for short options
       too.

       -e, --echo
              treat each ARG as an input line

       -i, --input-range=LO-HI
              treat each number LO through HI as an input line

       -n, --head-count=COUNT
              output at most COUNT lines

       -o, --output=FILE
              write result to FILE instead of standard output

       --random-source=FILE
              get random bytes from FILE

       -r, --repeat
              output lines can be repeated

       -z, --zero-terminated
              line delimiter is NUL, not newline

       --help display this help and exit

       --version
              output version information and exit

AUTHOR
       Written by Paul Eggert.

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
       Full documentation <https://www.gnu.org/software/coreutils/shuf>
       or available locally via: info '(coreutils) shuf invocation'

GNU coreutils 9.4                 April 2024                           SHUF(1)
本文 更新于: 2026-03-06 09:52:35 创建于: 2026-03-06 09:52:35