当我们提供非现有文件的名称时,Vim会创建新文件.这对我来说是不可取的,因为有时候我会给出错误的文件名并且无意打开文件,然后关闭它.
有没有办法阻止Vim打开新文件?例如,当我这样做时vi file1,它应该说File doesn't exist并留在bash终端上(没有打开vi窗口)
如果您使用写入(例如,:w或:x等效:wq)选项,它将仅保存文件.
:q相反退出,不会创建任何文件.
您可以将此函数添加到.bashrc(或等效文件)中。在调用vim之前,它将检查其命令行参数是否存在。如果您确实要创建一个新文件,则可以通过--new以覆盖检查。
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[@]}"
}
Run Code Online (Sandbox Code Playgroud)