Shell 编程:从命令输出中选择随机行

use*_*605 5 macos shell

我正在尝试创建一个简单的 Shell 脚本,其中涉及从当前工作目录中选择一个随机目录,然后导航到该目录。

谁能说明如何列出所有目录,并从该列表中随机选择一个?

我试图避免将所有目录列出到文本文件中,而只是从该文件中选择随机行(这很简单)。

我最初的尝试包括使用ls -d */命令仅列出目录。该命令在输入终端时有效,但返回错误:

ls: */: No such file or directory
Run Code Online (Sandbox Code Playgroud)

当我尝试将其实现到这个脚本中时:

DIR_LIST=` ls -d */`

echo "$DIR_LIST"
Run Code Online (Sandbox Code Playgroud)

sor*_*bet 4

find . -maxdepth 1 -type d ! -path . | shuf -n 1


shuf版本:

# To exclude hidden directories, use -name like so:
# find ... -name ".*"

# A version of find using only POSIX options:
# This might be slower for large directories (untested). Will need to be modified to list anything other than current directory.
# dirs="$(find . -type d ! -path "./*/*" ! -name ".")"

# Includes hidden directories.
dirs="$(find . -maxdepth 1 -type d ! -path .)"

numlines="$(printf "%s\n" "${dirs}" | wc -l)"
lineno="$((${RANDOM} % ${numlines} + 1))"
random_line="$(printf "%s\n" "${dirs}" | sed -n "${lineno}{p;q}")"

echo "Your selected directory: ${random_line}"
Run Code Online (Sandbox Code Playgroud)

编辑:根据评论改进代码。