bash 列出文件夹中的所有子目录,将它们写入数组以在菜单中使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28393843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash list all subdirectories in a folder, write them to array to use in a menu
提问by mike atkinson
I am in the middle of writing a bash script, I have multiple subfolders in a certain directory, I want to list the names of the subfolders and read the results into an array omitting a certain single folder called 'cmmdm' from the results. Once I have read the names into the array I want to generate a menu with each submenu name as a choice which I will then perform a function on the given subfolder depending on which choice the user makes.
我正在编写 bash 脚本,我在某个目录中有多个子文件夹,我想列出子文件夹的名称并将结果读入一个数组,从结果中省略一个名为“cmmdm”的单个文件夹。一旦我将名称读入数组,我想生成一个菜单,其中每个子菜单名称作为一个选择,然后我将根据用户所做的选择对给定的子文件夹执行一个功能。
EDIT: sorry should have added my initial code:
编辑:抱歉应该添加我的初始代码:
#!/bin/bash
# - create array
declare -a CDARRAY
# - set 0 to exit in prep for menu
CDARRAY[0]=exit
# - create a counter to use in while loop
count=1
# - while loop to itterate through folder and add each folder except cmmdm into array
ls -d /home/nginx/domains/* | {
while read CMMDOMAIN ; do
if [ $CMMDOMAIN != "/home/nginx/domains/cmmdm" ]
then
$CDARRAY[$count]=$CMMDOMAIN
echo $CDARRAY[$count]
count=$[count + 1]
fi
done
}
This does go through the folders and does ignore 'cmmdm' however my code to add the variable CMMDOMAIN to the array is wrong. I have never written a script in bash before so I think probably I've gotten the syntax wrong or missing some braces or something
这确实会遍历文件夹并忽略“cmmdm”,但是我将变量 CMMDOMAIN 添加到数组的代码是错误的。我以前从未用 bash 编写过脚本,所以我想可能是我的语法错误或缺少一些大括号或其他东西
回答by gniourf_gniourf
Your code has a lot of issues, too many to be discussed here (no offense).
您的代码有很多问题,太多无法在此讨论(无意冒犯)。
Here's a full example that will show a menu as you want, and does some common checking:
这是一个完整的示例,可以根据需要显示菜单,并进行一些常见检查:
#!/bin/bash
shopt -s extglob nullglob
basedir=/home/nginx/domains
# You may omit the following subdirectories
# the syntax is that of extended globs, e.g.,
# omitdir="cmmdm|not_this_+([[:digit:]])|keep_away*"
# If you don't want to omit any subdirectories, leave empty: omitdir=
omitdir=cmmdm
# Create array
if [[ -z $omitdir ]]; then
cdarray=( "$basedir"/*/ )
else
cdarray=( "$basedir"/!($omitdir)/ )
fi
# remove leading basedir:
cdarray=( "${cdarray[@]#"$basedir/"}" )
# remove trailing backslash and insert Exit choice
cdarray=( Exit "${cdarray[@]%/}" )
# At this point you have a nice array cdarray, indexed from 0 (for Exit)
# that contains Exit and all the subdirectories of $basedir
# (except the omitted ones)
# You should check that you have at least one directory in there:
if ((${#cdarray[@]}<=1)); then
printf 'No subdirectories found. Exiting.\n'
exit 0
fi
# Display the menu:
printf 'Please choose from the following. Enter 0 to exit.\n'
for i in "${!cdarray[@]}"; do
printf ' %d %s\n' "$i" "${cdarray[i]}"
done
printf '\n'
# Now wait for user input
while true; do
read -e -r -p 'Your choice: ' choice
# Check that user's choice is a valid number
if [[ $choice = +([[:digit:]]) ]]; then
# Force the number to be interpreted in radix 10
((choice=10#$choice))
# Check that choice is a valid choice
((choice<${#cdarray[@]})) && break
fi
printf 'Invalid choice, please start again.\n'
done
# At this point, you're sure the variable choice contains
# a valid choice.
if ((choice==0)); then
printf 'Good bye.\n'
exit 0
fi
# Now you can work with subdirectory:
printf "You chose subdirectory \`%s'. It's a good choice.\n" "${cdarray[choice]}"
The comments should explain pretty clearly what's going on. The technique used to build the array, and that was the purpose of your question, is extended globs. For example:
评论应该非常清楚地解释发生了什么。用于构建数组的技术,这就是您的问题的目的,是扩展 globs。例如:
shopt -s extglob nullglob
cdarray=( /home/nginx/domains/!(cmmdm)/ )
will populate cdarray
with all subdirectories of /home/nginx/domains/
that don't match cmmdm
(exact, full match). To have all subdirectories that don't end with a
or b
:
将填充不匹配的cdarray
所有子目录(完全匹配)。要拥有不以or结尾的所有子目录:/home/nginx/domains/
cmmdm
a
b
shopt -s extglob nullglob
cdarray=( /home/nginx/domains/!(*[ab])/ )
回答by Sigve Karolius
Could findbe something for you?
能找到适合你的东西吗?
DIRS=$(find ${PWD} -maxdepth 1 -type d)
echo ${DIRS}
Or maybe a for-loop (this will require you to make the array yourself)?
或者可能是一个 for 循环(这将需要您自己制作数组)?
for DIR in $(find ${PWD} -maxdepth 1); do if $(test -d ${DIR}); then echo $(basename ${DIR}); fi; done
I have been told that using "Internal Field Separator" (IFS) as shown below is an even more safe solution (protecting against weirdness, e.g. white characters, in fild/directory names)
有人告诉我,使用如下所示的“内部字段分隔符”(IFS)是一种更安全的解决方案(防止出现奇怪的现象,例如文件/目录名称中的白色字符)
while IFS= read -r DIR; do echo "${DIR}"; done < <(find . -maxdepth 1 -type d -printf "%P\n")