1

I should change directory to "foo" when it comes available. How to do it? This far I've came up with:

cd `ls | grep foo`

But the problem with that is that if there is no match for grep, the directory is changed to home directory.

Another approach I had was using:

ls -1 | grep foo | xargs -r cd

In this example -r takes care of not running the command if there is no match. But it doesn't work since cd command is shell build-in and not an executable. Or something like that..

[edit] Thanks for answers. If possible, could you also say how to combine mentioned functionality around grep somehow, so that I could use advanced regexp?

3 Answers 3

1

This will operate only on directories and will stay in the same directory if none is found:

cdg () {
    cd $(ls -d */ | grep "$1" || echo .)
}

If more than one directory matches, it will change into the first in the list.

3

How about trying this?

test -d foo && cd foo

You can then put this as a function in your .bashrc or something:

# conditional cd, use as follows:
# ccd some_dir
function ccd {
    test -d "$1" && cd "$1"
}

To use grep instead of a simple test -d, use the following (note that you can use another grep, or add flags as you wish):

# conditional regex-cd
functino rccd {
    if has_dir=`ls |egrep "$1"`; then cd $has_dir; fi
}

// Edited to match updated question.

2
if [[ -d foo ]]; then
  cd foo
fi

-d means "file exists and is a directory." This is in the "CONDITIONAL EXPRESSIONS" section of man bash.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .