Reputation: 2118
I have a number of directories I want to enter and all start with the same string "example". Beyond, in the same location, there are also other directories that I do NOT want to enter. I was used to loop in this way:
for dir1 in */
before other directories with other names were present in the same location, but now I cannot anymore. I tried to vary the command using:
for dir1 in "example"*/
or for dir1 in example*/ cd "dir1"
but it does not enter the directory.
It says: line 8: cd: example*//: file or directory does not exist
.
How can I do that?
Upvotes: 0
Views: 653
Reputation: 189910
The shell expands the wildcard
for dir1 in */
into a list of wildcard matches;
for dir1 in ack/ bar/ foo/ nst/ pth/ quux/
If you want to exclude foo
and bar
from this list, the simplest to explain is to enable extended globbing, assuming you have Bash;
shopt -s extglob
for dir1 in !(foo|bar)*/
but any trick to exclude the files you don't want from matching the wildcard is okay. In this particular case, you could do
for dir1 in [!bf]*/
but in the pessimal case, you just have to break down and list the directories you do want to match. Or maybe just bypass the undesired ones separately:
for dir1 in */; do
case $dir1 in bar|foo) continue ;; esac
: ... your code here
done
If indeed you want to loop over all the directories whose names start with example
and no others, then the way to do that is certainly
for dir1 in example*/
The error message you got seemed to indicate that there are no directories with this name.
Upvotes: 1
Reputation: 2567
Bash file name globbing is a slick thing. It may be more convenient to use find instead. Like this:
for dir in `find /cygdrive/c/workspaces/ -name '*log*' -a -type d`; do echo $dir; done
'-type d' is for directories only.
Upvotes: 0
Reputation: 14979
You can try this bash
one liner,
for dir in example*; do if [ -d $dir ];then cd $dir; pwd; echo $dir; fi; done
Bash script,
#!/bin/bash
for dir in example*
do
if [ -d $dir ];then
cd $dir;
pwd;
echo $dir;
fi
done
Upvotes: 0