1

I have to create 50 folders and each fifth folder should have 2*2 files in it, e.g

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

here is my code :

#!/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
1
  • 3
    Why is this question marked with python tag? Commented May 26, 2016 at 0:14

2 Answers 2

2

The problem with this is that you cd into a directory but you never cd back.

The simplest way of fixing this is by adding parentheses around the cd. These parentheses start a subshell, so the cd stays within it:

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

This is equivalent to but shorter than a manual cd ..:

for (( f = 0; f < n; f++ )) do
  cd Folder$countFolder && { touch File$f.txt; cd ..; }
done
Sign up to request clarification or add additional context in comments.

1 Comment

Or just touch Folder$countFolder/File$f.txt
1

You need to go into the directory, make your files, then leave. The most efficient way to do this is the following:

#!/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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.