I would like to do this in Bash:
I\'ve been playing around with th
pattern="foo"
for _dir in *"${pattern}"*; do
[ -d "${_dir}" ] && dir="${_dir}" && break
done
echo "${dir}"
This is better than the other shell solution provided because
${dir}
will be empty)=~
operator (if you need this depends on your pattern)find
)for example:
dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"
or (For the better shell solution see Adrian Frühwirth's answer)
for dir1 in *
do
[[ -d "$dir1" && "$dir1" =~ foo ]] && break
dir1= #fix based on comment
done
echo "$dir1"
or
dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"
Edited head -n1 based on @ hek2mgl comment
Next based on @chepner's comments
dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')
or
dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)
You can use the -quit
option of find
:
find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit