Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 1 down vote accepted

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.

share|improve this answer

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.

share|improve this answer
if [[ -d foo ]]; then
  cd foo

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

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.