1

Recently I started working with shell scripting in Linux (newbie). I wanted to know the commands or the procedure to change from one folder to another within the loop? I mean how can I call different folders inside the executing loop? Presently, I'm renaming all the folders with no's say 1,2,3..... and using these inside the loop. I know this is not a good way to use scripting.

set k=1
while ( $k <= 17)

## initial path set
    cd /home/naren/Documents/BASELINE_INSP/FreeSurfer/$k/RSFC

Each time 'k' updates, move to different folders since I named all folders as no's.

4 Answers 4

2

Try this:

#!/bin/bash
for ((i=1; i <= 17; i++)); do
    #Changing folder inside the loop
    cd "/home/naren/Documents/BASELINE_INSP/FreeSurfer/${i}/RSFC"
    #Here you can execute something more if you want
done
Sign up to request clarification or add additional context in comments.

Comments

1
#
# Start with ID equal to zero and increment
#
ID=0

#
# then use a say a while loop
#
while [ ${ID} -lt 5 ]; do 
    echo "my dir is /here/${ID}/there"; 
    ((ID++)); 
done

2 Comments

Although this code might solve the problem, a good answer requires an explanation of how/why this code helps.
I wouldn't write hybrid bash/POSIX code like this. The while loop is the correct method in POSIX, but then you must use something like ID=$((ID + 1)) to increment the variable. If you can use ((...)), then you could also more easily use a C-style for loop.
1

I mean how can I call different folders inside the executing loop?

Preferably, if you want to loop for all folders matching a certain pattern (which needn't contain numbers), just specify the pattern in a for loop:

for folder in /home/naren/Documents/BASELINE_INSP/FreeSurfer/*/RSFC
do  cd "$folder"
    # do something there
done

Comments

-1

In order to write your code without numeration, you can use ls command which lists the files in the current directory or use ls [folder_name] to list the files in a folder, In order to assign the result to file use $ operator
Edit:
since ls has some pitfalls as @randomir mentioned it is better to use iteration as following:

for f in ./* do
  //do something with $f
done

2 Comments

You should never do that.
Yeah you are right it seems the right way is something like that for file in somepath/*; do [ -e "$file" ] || continue some command "$file" done according to link

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.