How to stop Vim from creating/opening a new file?

vi, vim

Solution

You could add this function to your .bashrc (or equivalent). It checks that its command-line arguments exist before it invokes vim. If you really want to create a new file you can pass `--new` to override the checks.

vim() {
    local args=("$@")
    local new=0

    # Check for `--new'.
    for ((i = 0; i < ${#args[@]}; ++i)); do
        if [[ ${args[$i]} = --new ]]; then
            new=1
            unset args[$i]   # Don't pass `--new' to vim.
        fi
    done

    if ! (( new )); then
        for file in "${args[@]}"; do
            [[ $file = -* ]] && continue   # Ignore options.

            if ! [[ -e $file ]]; then
                printf '%s: cannot access %s: No such file or directory\n' "$FUNCNAME" "$file" >&2
                return 1
            fi
        done
    fi

    # Use `command' to invoke the vim binary rather than this function.
    command "$FUNCNAME" "${args[@]}"
}

Problem

Vim creates new files when we give name of a non existing file. This is undesirable to me, as sometimes I give wrong file name and have no intention to open a file, and then close it. Is there a way that will stop Vim from opening new files? For example, when I do `vi file1`, it should say `File doesn't exist` and stay on the `bash` terminal (without opening `vi` window)

Original source