korann
korann

Reputation: 13

Bash shell scripting

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.

Upvotes: 1

Views: 134

Answers (4)

kirecligol
kirecligol

Reputation: 876

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

Upvotes: -1

Armali
Armali

Reputation: 19375

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

Upvotes: 1

OscarAkaElvis
OscarAkaElvis

Reputation: 5714

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

Upvotes: 2

doktoroblivion
doktoroblivion

Reputation: 428

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

Upvotes: 1

Related Questions