BASH:编写脚本以递归方式移动N级目录

前端之家收集整理的这篇文章主要介绍了BASH:编写脚本以递归方式移动N级目录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下目录结构,例如:
  1. /test_dir/d
  2. /test_dir/d/cron
  3. /test_dir/d/cache
  4. /test_dir/d/...(more sub dirs)
  5. /test_dir/tree
  6. /test_dir/tree/a
  7. /test_dir/tree/a/a1
  8. /test_dir/tree/a/a2
  9. ...(and so on for b/ and c/ )

我编写了以下bash脚本,它有效地传递到/ test_dir的第二级,因此它将到达/ test_dir / d / cron或/ test_dir / tree / a但不会更进一步.我无法弄清楚为什么递归脚本不会进一步传播有人请调试脚本并指出我的错误

这是我写的:

  1. #!/bin/bash
  2.  
  3. #script to recursively travel a dir of n levels
  4.  
  5. function traverse() {
  6.  
  7. for file in `ls $1`
  8. do
  9. #current=${1}{$file}
  10. if [ ! -d ${1}${file} ] ; then
  11. echo " ${1}${file} is a file"
  12. else
  13. #echo "entering recursion with: ${1}${file}"
  14. traverse "${1}/${file}"
  15. fi
  16. done
  17. }
  18.  
  19. function main() {
  20. traverse $1
  21. }
  22.  
  23. main $1

这是输出

  1. /test_dir/a is a file
  2. /test_dir/b is a file
  3. /test_dir//dcache is a file
  4. /test_dir//dcron is a file
  5. /test_dir//dgames is a file
  6. /test_dir//dlib is a file
  7. /test_dir//dlog is a file
  8. /test_dir//drun is a file
  9. /test_dir//dtmp is a file
  10. /test_dir/movies is a file
  11. /test_dir//treea is a file
  12. /test_dir//treeb is a file
  13. /test_dir//treec is a file
  14. /test_dir//treed is a file

我知道可能有更优雅的一行命令来做到这一点.但我试图以这种明确的方式做到这一点.我为这篇文章的篇幅道歉.

编辑:使用遍历“${1} / ${file}”

脚本有几个问题.它应该是这样的:
  1. #!/bin/bash
  2.  
  3. #script to recursively travel a dir of n levels
  4.  
  5. function traverse() {
  6. for file in "$1"/*
  7. do
  8. if [ ! -d "${file}" ] ; then
  9. echo "${file} is a file"
  10. else
  11. echo "entering recursion with: ${file}"
  12. traverse "${file}"
  13. fi
  14. done
  15. }
  16.  
  17. function main() {
  18. traverse "$1"
  19. }
  20.  
  21. main "$1"

但是,递归遍历目录的正确方法是使用find命令:

  1. find . -print0 | while IFS= read -r -d '' file
  2. do
  3. echo "$file"
  4. done

猜你在找的Bash相关文章