문제

I am about to write a shell script to edit some files.

I'm doing it like this:

/usr/bin/vim $file

Now i want to ask the exit status of vim. If the user closes with saved changes do something (:wq or :x), or if closed without changes (:q, :q!) do something else

if [ vi-exit-status=wq ] ; then
    # do this
else # vi didn't save anything
    # do that
fi

How can I do that? When I call vi to create a new file and exit it without saving (:q!) and then I check the status via

echo $?

the answer is 0. If I save something or create a file via vi/vim, it's also 0.

Kind regards

도움이 되었습니까?

해결책

The exit status doesn't tell you what the user did in vim. Perhaps you could compare the timestamp on the file before and after to see if it was written to?

This works for me:

echo Edit me > editme.txt
time1=`stat -c%y editme.txt`
vim editme.txt
time2=`stat -c%y editme.txt`
if [ "$time1" != "$time2" ]; then
    echo You saved it.
else
    echo No change.
fi

다른 팁

Exit status is different from only if an application has failed.

In you case i suggest you:

  1. save current md5sum to a variable
  2. open vim
  3. save current md5sum to a variable
  4. compare both

The only way to influence the exit status of Vim is by using :cquit, but users typically don't do that.

What you rather want is an indication of whether the file has been modified by Vim. You can do this by checking the modification time before and after editing, like in this Bash snippet:

EDIT=/path/to/file.txt
MODTIME=$(stat -c %Y "$EDIT")
"$EDITOR" "$EDIT" || { echo 2>&1 "Unclean exit of editor; aborting!"; exit $?; }
NEWMODTIME=$(stat -c %Y "$EDIT")

if [ $NEWMODTIME -eq $MODTIME ]; then
    echo "No changes done."
    exit 0
fi
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top