Home > Software design >  Bash; change directory to folders start with 2* or 21*
Bash; change directory to folders start with 2* or 21*

Time:03-23

I have a series of folders which are named based on the date of creation and some other information; i.e.

220310_AS
220307_DF
220228_1A
..
211228_QR
..
201224_HH

How can I in a bash script loop over folders which start with 22 or 21? Here is part of my code which does not work

..
for dd in */2*; do
    cd "$dd"
    #do something
    eval "ls"
    cd ..
..

CodePudding user response:

Your wildcard */2* matches directories 2 levels below the original directory. So to get back to the original directory, you need cd ../.. instead of cd ...

You could also do the cd in a subshell, then simply exiting the shell will return you to the original directory.

for dd in */2*; do (
    cd "$dd"
    # do stuff
); done
  • Related