linux - Shell,For循环进入目录和子目录未按预期工作

标签 linux bash shell for-loop recursion

当尝试做一个简单的脚本来将文件打包并将它们移动到另一个目录时,我在实现递归循环时遇到了问题。

#!/bin/bash
for directorio in $1; do #my thought process: start for loop goes into dir
    for file in $directorio; do #enter for loop for files
        fwe="${file%.*}" #file_without_extension    
        tar -czPf "$fwe.tar.bz2" "$(pwd)" && mv "$fwe.tar.bz2" /home/cunha/teste
    done
done

脚本似乎什么也没做...... 当脚本被调用时:./script.sh/home/blablabla

我怎样才能解决这个问题?

最佳答案

您可以更好地遵循以下选项。它将如何运作?首先,它会列出 short_list.txt 中的所有目录。在 while 循环中,它将读取每个目录名称并将其压缩到位置 /home/cunha/teste

find $1 -type d -name "*" > short_list.txt
cdr=$(pwd)

while read line
do
   cd $line
   base=$(basename $PWD)
   cd ..
   tar -cf /home/cunha/teste/$base.tar.gz  $base
done < short_list.txt
cd $cdr
rm -rf short_list.txt

关于linux - Shell,For循环进入目录和子目录未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512941/

相关文章:

c - OpenGL矩形动画

linux - 验证条件检查的目录路径 (bash)

bash - 参数扩展默认值到空数组

linux - 你如何区分一个目录只包含特定类型的文件?

bash - 如何在 bash 中循环遍历字母表的前 n 个字母

shell - 如何将命令参数中的引号转义为 sh -c?

python - 如何在 x 时间后重新启动 python 脚本?

windows - 在 linux 上编译 windows 屏保

linux - 使用额外的 tty session 耗尽电池生命周期?

linux - 为什么我无法在本地主机上访问 Xampp 的 phpmyadmin?禁止访问。