简体   繁体   English

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

[英]Script to pick random directory in bash

I have a directory full of directories containing exam subjects I would like to work on randomly to simulate the real exam. 我有一个充满目录的目录,其中包含我想随机模拟真实考试的考试主题。

They are classified by difficulty level: 它们按难度级别分类:

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

I am trying to write a shell script allowing me to pick one subject (directory) randomly based on the parameter I pass when executing the script (0, 1, 2 ..). 我正在尝试编写一个Shell脚本,允许我根据执行脚本时传递的参数(0、1、2 ..)随机选择一个主题(目录)。

I can't quite figure it, here is my progress so far: 我不太清楚,这是到目前为止的进展:

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

What am I missing here? 我在这里想念什么?

There's no need for any external commands ( ls , find , sort , head ) for this at all: 完全不需要任何外部命令( lsfindsorthead ):

#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM