代码之家  ›  专栏  ›  技术社区  ›  Wizzardzz

在bash中选择随机目录的脚本

  •  0
  • Wizzardzz  · 技术社区  · 7 年前

    我有一个目录,其中包含了我想随机模拟真实考试的考试科目。

    它们按难度等级分类:

    0-0, 0-1 .. 1-0, 1-1 .. 2-0, 2-1 ..
    

    我试图编写一个shell脚本,允许我根据执行脚本时传递的参数(0,1,2…)随机选择一个主题(目录)。

    我不太明白,这是我目前的进展:

    ls | find . -name "1$~" | sort -r | head -n 1
    

    我错过了什么?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Charles Duffy    7 年前

    不需要任何外部命令( ls , find , sort , head )为了这个:

    #!/usr/bin/env bash
    set -o nullglob       # make globs expand to nothing, not themselves, when no matches found
    dirs=( "$1"*/ )       # list directories starting with $1 into an array
    
    # Validate that our glob actually had at least one match
    (( ${#dirs[@]} )) || { printf 'No directories start with %q at all\n' "$1" >&2; exit 1; }
    
    idx=$(( RANDOM % ${#dirs[@]} ))  # pick a random index into our array
    echo "${dirs[$idx]}"             # and look up what's at that index