假设我们有一个目录名为“A”,有4个子目录(aa,bb,cc,dd),其中一些子目录还有子目录,所以假设如下图:
A
aa
aaa
bb
bbb
bbbb
cc
dd
我尝试在数组中列出子目录(aa,bb,cc,dd
),然后在我的脚本中按数组编号使用它们。
我使用下面的脚本将 dd
复制到父目录:
while IFS= read -d '' file; do
A+=( "$file" )
done < <(find . -type d -print0 | LC_ALL=C sort -z)
cp -r `pwd`/${A[4]}" `pwd`/..
但问题是脚本创建了所有子目录的数组,[aa aaa bb bbb bbbb cc dd]
所以 ${a[4]} = bbb
而不是 dd
。
知道如何修复它吗?
最佳答案
您可以使用 maxdepth
选项将 find
限制为仅查看顶级目录:
find . -type d -print0 -maxdepth 1 | LC_ALL=C sort -z
您可以使用 glob 以更简单的方式实现相同的目标:
dirs=(*/) # store all top level directories into the dirs array
dirs=("${dirs[@]%/}") # strip trailing / from each element of the array
然后
cp -r "$PWD/${dirs[4]}" "$PWD/.."
- 需要使用双引号来防止分词和通配符 反引号中的
pwd
可以简单地写成$PWD
,不需要创建子shell
关于arrays - 如何将子目录列表存储到数组中并通过 Bash 中的索引访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44743595/