How to change file permission from within vi

2019-03-17 22:30发布

I sometimes open a read-only file in vi, forgetting to do chmod +w before opening it. Is there way to change the file from within vi?

Something like !r chmod +w [filename]?

Is there a shortcut to refer to the currently open file without spelling it's long name?

标签: vim vi
6条回答
可以哭但决不认输i
2楼-- · 2019-03-17 22:58

I know this is an old post, but with Vim Version8 a function has been included with which you can change file permissions.

According to the version8.txt file:

setfperm() set the permissions of a file

This function can then be called via the "call" command in Vim.

This is done as follows:

:call setfperm("file name","permissions")

The structure of the "permissions" string takes the same form as described in the Vim documentation:

getfperm({fname}) getfperm() The result is a String, which is the read, write, and execute permissions of the given file {fname}. If {fname} does not exist or its directory cannot be read, an empty string is returned. The result is of the form "rwxrwxrwx", where each group of "rwx" flags represent, in turn, the permissions of the owner of the file, the group the file belongs to, and other users. If a user does not have a given permission the flag for this is replaced with the string "-". Example: :echo getfperm("/etc/passwd") This will hopefully (from a security point of view) display the string "rw-r--r--" or even "rw-------".

A minimal example:

:call setfperm("foo.txt","rwxrwxrwx")

This adds read, write and execute permissions to the "foo.txt" file in the current directory.

查看更多
Bombasti
3楼-- · 2019-03-17 23:04

If you have the rights to write to the file, then you can just use exclamation mark to force it:

:w!

If you don't have the rights and need to change user, but still want to write to the file, sometimes you may go for something like

:w !sudo tee %
查看更多
Lonely孤独者°
4楼-- · 2019-03-17 23:06
:!chmod <perms> <file>

and if vi still doesn't want to write it,

:se cpo-=W
查看更多
一夜七次
5楼-- · 2019-03-17 23:10

Have you tried

!chmod +w %

The % represents the current filename.

You could also map a key to this like Ctrl-W.

:map <C-w> :!chmod +w %<CR>

Note that you type Ctrl-V Ctrl-M to get the <CR>

查看更多
ら.Afraid
6楼-- · 2019-03-17 23:18

Just use

:!chmod +w %

in command mode. % will be replaced by the current file name.

查看更多
迷人小祖宗
7楼-- · 2019-03-17 23:22

After editing your file with vim, press "esc" and then ":". Then type the following command:

w !sudo tee %

Then press "Enter". Then type

:q!

to successfully exit from the editor.

查看更多
登录 后发表回答