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?


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.


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.

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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