You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Bash的select命令中动态包含指定目录并排除特定目录

问题与解决方案

问题背景

我正在编写一系列Bash脚本以自动化项目中的目录和文件创建,但Shell脚本能力有限。当前项目基础目录结构如下:

->
--> applications/
----> sub_dir1/
--> classes/
----> sub_dir1/
------> file1
------> file2
----> sub_dir2/
----> sub_dir3/
----> sub_dir4/

目前脚本进入classes/目录执行通用select代码,可动态列出所有子目录(新增目录也会自动纳入),但我希望排除一组静态子目录(含7个前缀为thing-*的目录和3个无共同前缀的目录),却不知如何整合排除逻辑。

解决方案

最终找到的稳健解决方案如下,该方案通过检测目录下是否存在直接嵌套的package.json文件来动态排除目标目录,满足团队项目目录管理需求:

# Start script
cd classes/

PS3="Which directory should this class be initialized in? Enter the corresponding number. "
shopt -s extglob

# START FILTER LOGIC
# assign all directories in classes/ to dirs array
dirs=(./*)
# find all directories with a package.json file one-level deep in dirs array
files=($(find . "${dirs[@]}" -maxdepth 1 -name "package.json"))
# remove package.json suffixes from identified directories
exclude=("${files[@]%%/"package.json"}")

dirsToPrint=()

# build new array of directories that are not in the exclude array
for dir in "${dirs[@]}"; do
  if ! [[ "${exclude[@]}" =~ "${dir}" ]]; then
    dirsToPrint+=("${dir}")
  fi
done

# display directories to print in user select list
select subdir in "${dirsToPrint[@]}"; do
  test -n "$subdir" && break
  echo ">>> Invalid Selection"
done
# END FILTER LOGIC
# Other logic continues from here

方案说明

  1. 切换到classes/目录,设置select的提示文本并开启扩展通配符支持
  2. 收集classes/下所有子目录到数组dirs中
  3. 通过find命令找出所有直接包含package.json文件的目录,处理后得到需要排除的目录数组exclude
  4. 遍历所有目录,将不在排除列表中的目录存入dirsToPrint数组
  5. 使用select让用户选择目标目录,输入无效时提示错误

内容的提问来源于stack exchange,提问作者Kayla Justice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 20:55:17