你的代码有很多问题,太多无法在这里讨论(没有冒犯)。
这里有一个完整的例子,只要你想,将显示一个菜单,并做了一些常见的检查:
#!/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]}"
的意见应该非常清楚地解释发生了什么事情。用于构建阵列的技术,这是您的问题的目的是extended globs。例如:
shopt -s extglob nullglob
cdarray=(/home/nginx/domains/!(cmmdm)/)
将填充cdarray
与/home/nginx/domains/
所有子目录不匹配cmmdm
(确切的说,全场比赛)。要具有不以a
或b
结尾的所有子目录:
shopt -s extglob nullglob
cdarray=(/home/nginx/domains/!(*[ab])/)
够简单。你为什么不尝试?你被困在什么地方? – SMA 2015-02-08 12:22:08
在Bash中,使用[extentded globs](http://www.gnu.org/software/bash/manual/bashref.html#Pattern-Matching):'shopt -s extglob nullglob; array =(dir /!(cmmdm)/)'。 – 2015-02-08 12:27:51
嗨,对不起,我已添加我的inital代码以查看im卡住的位置 – 2015-02-08 13:45:37