Bash directory loop, but only choose those folders with specific word in it

Hello, how in bash i can get directory loop, but only choose those folders with specific word in it, so it will only echo those with specific word

#!/bin/bash
for filename in /home/test/*
do
if [ -d "${filename}" ]; then
echo $filename;
fi

thx!

Try

for filename in /home/test/*word*
1 Like

Depending on what you are doing with $filename after determining that it names a directory, you might also be able to reduce the iterations through the loop by just looking for directories to start with:

for directoryname in /home/test/*word*/
1 Like

A trailing / ensures it is a directory

for filename in /home/test/*word*/

With your original loop, you can go for a case-esac, or, if there is only one pattern, go for a [[ == ]]

if [[ $filename == *word* ]] && [ -d "$filename" ]; then
  echo "$filename"
fi
1 Like

If you want to search deeper that just within the current directory (i.e. searching within subdirectories) you can use the find command:-

find /path/to/source -type d -name "*word*"

Be aware that this does not sort the output and will try to follow symbolic links and descend into sub-mounted filesystems. If these are a problem they can be turned off.

Does this help, or am I going the wrong way by using too big a tool for a simple job?

Robin

1 Like