简体   繁体   中英

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.

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

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM