Lukas Oppermann
Lukas Oppermann

Reputation: 2938

Bash/shell search for subfolder in current dir and cd into it

How would I go about search if the folder "test" is anywhere within my current dir and once the first occurrence is found automatically cd into it? Using the terminal on mac (bash).

Upvotes: 1

Views: 1663

Answers (5)

ruakh
ruakh

Reputation: 183251

You can write:

cd "$(find . -type d -name test -print -quit)"

(Caveat: this works for test, but will not work for any filename ending in newlines. Fortunately, I've never heard of anyone having a real filename that ended in a newline — it's possible, but never done — and the filename is an argument under your control. So I can't imagine that this will be a problem.)

Upvotes: 3

John B
John B

Reputation: 3646

You could use the globstar option of bash which searches directories recursively.

shopt -s globstar
for i in **/*test; do 
    if [[ -d $i ]]; then
        cd "$i"
        break
    fi
done

Upvotes: 1

blackSmith
blackSmith

Reputation: 3154

You can try :

if [ -d "test" ]; then cd test; fi

Or simply :

[ -d "test" ] && cd test

Upvotes: 0

Red Cricket
Red Cricket

Reputation: 10460

Or just do ...

cd test

... if test is a directory the you just cd'ed into it. If is not ... so what.

Upvotes: -1

dganesh2002
dganesh2002

Reputation: 2210

The below will work if that dir exists ->

cd `find . -name test -type d`

For bash I guess below should work ->

cd $(find . -name test -type d)

Upvotes: 2

Related Questions