我必须创建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
答案 0 :(得分:2)
这个问题是你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
答案 1 :(得分:1)
您需要进入目录,制作文件,然后离开。最有效的方法如下:
#!/bin/bash
n=1
declare -i countFolder
for (( countFolder = 1; countFolder <= 50; countFolder++ ))
do
mkdir Folder$countFolder
ls
done
for (( countFolder = 5; countFolder <= 50; countFolder = countFolder+5 ))
do
let "n = n * 2"
cd Folder$countFolder
for (( f = 0; f < n; f++ )) do
touch File$f.txt
done
cd ..
done