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

autocompletebash

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?

Best Answer

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
}