linux - 使用 bash 脚本创建文件夹和文件

标签 linux bash

我必须创建 50 个文件夹,每五个文件夹中应该有 2*2 个文件,例如

folder1
.
.
folder5 - has 2 files in it
folder 6
.
.
folder 10 - has 4 files in it 
.
.
folder 15 - has 8 files in it 

这是我的代码:

#!/bin/bash


n=1 
declare -i countFolder

for (( countFolder = 1; countFolder <= 50; countFolder++ )) 
do 
    mkdir Folder$countFolder
done

for (( countFolder = 5; countFolder <= 50; countFolder = countFolder+5 ))
do

    let "n = n * 2"

    for (( f = 0; f < n; f++ )) do
    cd Folder$countFolder && touch File$f.txt
    done
done

最佳答案

问题在于您cd 进入一个目录,但您永远不会cd 返回。

解决此问题的最简单方法是在 cd 两边添加括号。这些括号开始一个子 shell,因此 cd 留在其中:

for (( f = 0; f < n; f++ )) do
  ( cd Folder$countFolder && touch File$f.txt ) 
done

这等同于但短于手动cd ..:

for (( f = 0; f < n; f++ )) do
  cd Folder$countFolder && { touch File$f.txt; cd ..; }
done

关于linux - 使用 bash 脚本创建文件夹和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37449516/

相关文章:

php - 如何找出哪个代码正在使用 Sendmail?

linux - 如何在 linux shell 中检查数字是否偶数?

linux - 如何通过 BlueZ C 库执行蓝牙低功耗扫描

linux - 需要在 bash 中的两个给定时间之间生成时间值

linux - 保持 mplayer 窗口打开,链接顺序视频文件

git - 对每个更改的文件执行命令

linux - 来自 shell 的 GROUP BY/SUM

linux - 文件读取不解释环境变量

linux - 为 openssh 使用 pam_exec 的帐户的外部脚本

bash - 如何在shell脚本中生成uuid