我编写了一个脚本,我希望用户输入一个目录或多个目录,并且每个目录都检查一些对此讨论不重要的内容。所有的内部目录也被检查到指定的深度。参数名称中的Bash数组参数扩展:错误替换
虽然我可以声明数组Directories0
(输入目录)开始,但我无法以任何方式引用它...... result:错误的替换。显然,Directories1
将深度= 1,Directories2
是深度= 2,依此类推......
下面的代码片段:
let Recurse=4 ## say... variable value ##
[ "$Recurse" ] && let MaxDepth="$Recurse" || let MaxDepth=0
declare -i depth=0
IFS=$'\n'
## declare -a Directories${depth}=("${@}") ## <—— doesn't work
## declare -a Directories${depth}="("${@}")" ## <—— works if the brackets only are quoted...
## declare -a Directories${depth}=\("${@}"\) ## <—— ... or escaped
declare -a "Directories${depth}=("${@}")"
IFS=$' \t\n'
## Nested loop, depth counter increases for each directory depth. I want to stop at a specific depth which is entered as an option ##
for ((depth = 0; depth <= MaxDepth; depth++)); do ## MaxDepth is entered as option ##
until [ -z "${Directories${depth}[*]}" ]; do ## ***** bad substitution error ***** ##
declare input="$(follow "${Directories${depth}[0]}")" ## follow is a script that resolves symlinks and Finder aliases ##
CheckDirectory "${input%/}/" ## check directory ##
case $? in
## Tests passed ##
0) if [[ "$Recurse" && "$depth" -lt "$MaxDepth" ]]; then
IFS=$'\n'
## get ready to check sub-directories ##
declare -a Directories$((depth + 1))="("${Directories$((depth + 1))[@]}" $(find -P "${Directories${depth}[0]}" -type d -mindepth 1 -maxdepth 1 -exec follow '{}' \;))"
IFS=$' \t\n'
fi
true;;
## Tests failed ##
*) false;;
esac
[ $? -eq 0 ] && unset Directories${depth}[0] || exit 1 ## if test fails, exit, if succeeds, move on to next directory ##
declare -a Directories${depth}="("${Directories${depth}[@]}")" ## re-shuffle the array to get rid of null value at index 0 ##
((element++))
done
done
下面是一个简化版本的情况下,你不想去通过上面的代码,这就是问题的症结所在:
depth=2
declare -a "Directories${depth}=(yo man ma me mo)"
echo "${Directories${depth}[4]}"
> -bash: ${Directories${depth}[4]}: bad substitution
echo "${Directories2[4]}"
> mo
解决方案,任何人吗?
- Aesthir
用'的问题eval'是我似乎无法做**任何事情*阵列***。无论IFS设置为什么,eval都会分解包含空格的元素。我尝试过,但无济于事...这是一个挑战,试着让我发布的代码作为使用'eval'工作的问题......我能想到的唯一方法就是循环遍历每个元素我希望使用eval。对于初学者,***没有循环*,使用'eval'从底部的第4行开始工作(重新洗牌)。如果'eval'真的*可以*做到这一点,我相信这将是一个简单的一行。** – Aesthir