How to fuzzy complete filenames in bash like vim's ctrlp plugin?

5

Say my pwd is at ~/myproject/ and I have a file in ~/myproject/scripts/com/example/module/run_main_script.sh

In vim with ctrlp plugin, I can press Ctrl+P, type run_main_ Enter, I am editing that script.

I want to run that script (with some arguments) in bash. And I don't want to type the full path. Is there any way to do that in bash?

fqsxr

Posted 2012-11-05T08:33:26.127

Reputation: 155

Answers

1

That's what normally the PATH variable is for. Though, I would not add your whole home-directory to your PATH. Consider adding a dedicated directory (like ~/bin) to add to your path your executables.

However, you could add a function to your ~/.bashrc which allows you to search for and run a script...something like this:

# brun stands for "blindly run"
function brun {
    # Find the desired script and store
    # store the results in an array.
    results=(
        $(find ~/ -type f -name "$1")
    )

    if [ ${#results[@]} -eq 0 ]; then   # Nothing was found
        echo "Could not find: $1"
        return 1

    elif [ ${#results[@]} -eq 1 ]; then   # Exactly one file was found
        target=${results[0]}

        echo "Found: $target"

        if [ -x  "$target" ]; then   # Check if it is executable
            # Hand over control to the target script.
            # In this case we use exec because we wanted
            # the found script anyway.
            exec "$target" ${@:2}
        else
            echo "Target is not executable!"
            return 1
        fi

    elif [ ${#results[@]} -gt 1 ]; then   # There are many!
        echo "Found multiple candidates:"
        for item in "${results[@]}"; do
            echo $item
        done
        return 1
    fi
}

Bobby

Posted 2012-11-05T08:33:26.127

Reputation: 8 534

This is a great script! I changed a bit to meet my need: ` results=($(find ~/ -name "$1")) => results=($(find ./ -type f -name "$1*"))

exec $target ${@:2} => $target ${@:2} ` – fqsxr – 2012-11-06T02:41:29.573

@fqsxr: -type f is good idea, yeah. – Bobby – 2012-11-06T08:10:48.433

1

I also wanted this.
I wrote this little perl script for that, feel free to check it out.
Ctrl-P like command line (bash) script.

hmepas

Posted 2012-11-05T08:33:26.127

Reputation: 11

0

Not exactly what you are looking for, but is pretty good, and built right into the bash you already are using is Ctrl-r http://ruslanspivak.com/2010/11/20/bash-history-reverse-intelligent-search/

It would be nice if it was more fuzzy, like ctrlp in vim. There are some higher level implementations mentioned here Is there a shell which supports fuzzy completion as in Sublime Text?

You can trick out your entire bash prompt to be more vim-like use readline and .inputrc http://vim.wikia.com/wiki/Use_vi_shortcuts_in_terminal

Zak

Posted 2012-11-05T08:33:26.127

Reputation: 115