5

I have a bunch of directories:

20130118-Cars_Directory
20130118-Bikes_Directory
20130218-Planes_Directory
20130228-Scooters_Directory

Is there any way to change directories in the manner of typing a partial match in the middle of the command.

Ideally, something in the style of cd *Bikes*<TAB>, and have dash autocomplete the rest?

4 Answers 4

7

You can do that by creating an alias for cd and defining a bash completion as your will. See Bach Completion manual.

Here is a step by step guide. I will use "scd" for our new command, but you can use "cd" as well.

1) Editing .bashrc file

gedit ~/.bashrc  

2) Creating the alias
Paste this in the final of the ".bashrc" file:

# Alias for making a "Super cd"

alias scd="cd"

_scd_completion() {
    mapfile -t COMPREPLY < <(ls -d */ | grep "${COMP_WORDS[COMP_CWORD]}")
}
complete -F _scd_completion scd

Save and close.

3) Open a new terminal
Or run: source ~/.bashrc

4) How to use

Just call the command followed by part of the name of the directory you want to go.

scd Bikes<TAB>

Done. Enjoy!

2
  • Perfect! And what a good solution ... this speeds up my navigation in Terminal a lot. Thank you for tanking the time to code the bash completion.
    – somethis
    Mar 31, 2013 at 14:01
  • Best regards ;-)
    – desgua
    Mar 31, 2013 at 14:58
3

Actually, by coincidence, it turns out that cd *Bikes*<RETURN> works without any changes to the system.

I am just a little stunned that it didn't require quotes around *Bikes*.

2

Try to use the tool called z, it allows what you need, plus it creates a global database of your cd's weighted by frequency and allows you to jump to frequently visited place instantly.

If you have visited the Bikes directory, you can later type

z Bikes

and you will jump there

1
  • Can you elaborate how to use z for what the user had asked for?
    – orschiro
    Sep 16, 2016 at 9:27
1

The answer from desuga works, but it is case sensitive.

If you do not want it to be case sensitive, the ~/.bashrc file should be:

# Alias for making a "Super cd"

alias scd="cd"

_scd_completion() {
    mapfile -t COMPREPLY < <(ls -d */ | grep -i "${COMP_WORDS[COMP_CWORD]}")
}
complete -F _scd_completion scd

You must log in to answer this question.

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