在 Bash select 中动态包含特定目录并排除其他目录

问题描述 投票:0回答:1

我正在编写一系列 bash 脚本来自动在项目中创建目录和文件。我对 shell 脚本的工作熟练程度有限。

这是基本的项目目录结构:

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

目前,我的脚本导航到

classes/
并执行这个包罗万象的
select
代码,这是我从 here 抄来的。

select d in */; do
  test -n "$d" && break
  echo ">>> Invalid Selection"
done

这将按预期动态列出

classes/
下的所有子目录。如果我在
sub_dir5/
下添加
classes/
并使用此代码片段重新运行脚本,则会填充
sub_dir5/
,这就是我想要的...

...除了有一组静态子目录,我想从中排除

select
,同时保留动态生成新添加的子目录的功能。

我尝试创建要排除的静态目录数组(例如

directoriesToExclude=("sub_dir2" "sub_dir4")
,但我不知道如何将该变量合并到上面的
select
中。我查看了使用
find
 的示例prune
not
,各种循环,各种条件,我想不通……

有帮助(或者可能没有),我想排除七个具有相同前缀(例如

thing-*
)的子目录,以及不共享该前缀的其他三个子目录。我知道有一种方法可以将具有相同命名约定的目录/文件集中在一起,但我又不知所措。感谢您的帮助!

bash shell terminal conditional-statements
1个回答
0
投票

要从选择循环中排除特定子目录,您可以修改代码以过滤掉要排除的目录。我将为您提供一个如何实现这一目标的示例。

首先,让我们创建一个包含要排除的静态目录的数组。您提到有七个子目录具有相同的前缀(例如,thing-*),而其他三个子目录不共享该前缀。我们将使用这些信息来构建我们的排除列表。

#!/bin/bash  
# Define the static directories to exclude

declare -a directoriesToExclude=("sub_dir2" "sub_dir4" "thing-1" "thing-2" "thing-3" "thing-4" "thing-5" "thing-6" "thing-7")

# Dynamically list all sub-directories under classes/
select d in */; do
  # Check if the selected directory is non-empty and not in the exclusion list
  if [[ -n "$d" && ! " ${directoriesToExclude[@]} " =~ " $d " ]]; then
    break
  else
    echo ">>> Invalid Selection"
  fi
done

# Now you can use the selected directory ($d) for further processing
echo "Selected directory: $d"
© www.soinside.com 2019 - 2024. All rights reserved.