How To Save A File In Vim / Vi Without Root Permission With sudo

This happens lot of times. I login as a normal user and start to edit httpd.conf or lighttpd.conf or named.conf in vim / vi text editor. However, I’m not able to save changes due to permission issue (all config files are owned by root). How do I save file without creating a temporary file (/tmp/httpd.conf) and then move the same (mv /tmp/httpd.conf /etc/httpd) as root using vim / vi itself?

Tutorial details
Difficulty level Easy
Root privileges No
Requirements vim and sudo on Linux/macOS/Unix
Est. reading time 3 minutes
You can use the combination of sudo command (assuming that sudo is configured for your account) to save a file without creating a third file in /tmp. This is useful to write a privileged file with sudo command. For example saving a read-only file edited in vim and vi is possible with this trick.

Syntax to save a file in Vim without root permission with sudo

In this example, you will edit a file called /etc/apache2/conf.d/mediawiki.conf as a normal user:
$ vi /etc/apache2/conf.d/mediawiki.conf
Make some changes and try to save by pressing :w, enter:

Fig.01: Vim Cannot Open File (Permission Problem)

Fig.01: Vim Cannot Open File (Permission Problem)

To save a file, simply type the following command:
:w !sudo tee %

Fig.02: Save A File In Vim Without Root Permission With sudo

Fig.02: Save a file using sudo and tee

What the vim and shell command does:

  • :w – Write a file (actually buffer).
  • !sudo – Call shell with sudo command.
  • tee – The output of write (vim :w) command redirected using tee.
  • % – The % is nothing but current file name. In this example, it is /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input (or the buffer) and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
Fig.03: Save and Load File In Vim Again Without Login As Root

Fig.03: Save and Load File In Vim Again Without Login As Root

Update ~/.vimrc file

Open/Edit ~/.vimrc file and append the following code:

" Sample command W
command W :execute ':silent w !sudo tee % > /dev/null' | :edit!

Save and close the file. Open vim/vi and try to edit a privileged file with:
$ vi /etc/hosts
Now, write a privileged file with custom command just type W:

Fig.04 VIM write a privileged file custom W command

Fig.04 VIM write a privileged file custom W command

Now, sudo requires that you authenticate yourselves with a password:
Fig.05: Sudo in action inside vim

Fig.05: Sudo in action inside vim

A note about sudo config

Make sure you add yourself to sudo file. Here is my configuration (run ‘sudo visudo‘ OR ‘su -‘ and ‘visudo‘):

# User privilege specification
root    ALL=(ALL) ALL
%admin  ALL=(ALL) ALL

Make sure you add yourself to admin group:
# usermod -a -G admin vivek
# id vivek

Sample outputs:

uid=501(veryv) gid=20(staff) groups=20(staff),80(admin),81(_appserveradm),98(_lpadmin),33(_appstore),100(_lpoperator),204(_developer)

Try vim plugins to write/edit a privileged file or read only file

  • User Unix commands including sudo, chmod, and more without leaving vim ever!
  • This plugin enables vim to read files, using sudo or su or any other tool that can be used for changing the authentication of a user.


You just learned how to save a read-only file edited in vim text editor. As a sysadmin you might edit a file non-privileged user. In such case you can save file without login as root using the sudo command.

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 46 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersncdu pydf
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
46 comments… add one
  • James Mar 30, 2010 @ 21:09

    :w !sudo %
    does not work for me.

    • johnny Mar 13, 2015 @ 18:27

      you need to use
      :w !sudo tee %

  • Sebastian Kusnier Mar 30, 2010 @ 21:46

    “To save a file, simply type the following command:
    :w !sudo %”

    you forget tee in command

  • Steve Mar 30, 2010 @ 22:30

    Wow, I can’t believe I never thought of that before.

    I added this to my .vimrc that I sync on every machine I administrate based on what you wrote:

    if has(“unix”)
    command -nargs=? Swrite :w !sudo tee %

  • gregf Mar 31, 2010 @ 3:34

    I have a :SudoW command in my vimrc that does exactly this. I got it from some one else’s blog at some point and can’t seem to find out where, at this point. Here is the snippet though.

    command! -bar -nargs=0 SudoW :silent exe “write !sudo tee % >/dev/null” | silent edit!

  • 🐧 nixCraft Mar 31, 2010 @ 6:34


    Thanks for the head up! tee included in screen shot but somehow I forgot in command line.

  • 🐧 nixCraft Mar 31, 2010 @ 10:17


    Use :w !sudo tee %. It was a typo on my part.


  • Manoj Mar 31, 2010 @ 10:30

    not working for me

    :w !sudo tee%
    !sudo teea
    [No Valid Runas is Matched]
    Sorry, user xxxxx is not allowed to execute ‘teea’ as anyone on newss1.
    sudo: teea:command could not found.
    Check the path or specify path plus command.
    [Hit return to continue]
    No write since last change (:quit! overrides)
    [Hit return to continue]

    Tried with space as well after tee command


  • Philippe Petrinko Mar 31, 2010 @ 10:31

    Nice tip, thanks Vivek.

  • Jackson John Mar 31, 2010 @ 10:35

    Loved the Tip !!!!

  • 🐧 nixCraft Mar 31, 2010 @ 10:35


    Put a white space between tee and %
    :w !sudo tee %
    You must configure sudo. You use sudo for admin task, don’t you?, A typical /etc/sudoers for admin users:

    %admin ALL=(ALL) ALL

    And add your self to admin group (use usermod).

  • Daniel Reimann Mar 31, 2010 @ 10:36

    This is very useful, thank you for posting it.

  • justadreamer Mar 31, 2010 @ 10:38

    seems you are missing a space between tee and % in your command line

  • Manoj Mar 31, 2010 @ 10:42

    both the way i tried, seems sudo is not configured.

    I dont have sudo/root permissions, what should i do?

  • Vinod Dham Mar 31, 2010 @ 10:48


    Love it. Thanks for sharing it.

    BTW, I tried to reach earlier and your site was down for like hour or two.

  • Vinod Dham Mar 31, 2010 @ 10:50


    Only root user suppose to access and edit files in /etc. This is not a hacking or creaking attempt.

  • 🐧 nixCraft Mar 31, 2010 @ 10:53


    Our apologies for the temporary inconvenience. There was some sort of network issue. Let me know if you’ve any more problems.

  • Nic0 Mar 31, 2010 @ 11:42

    This is an awesome trick, but I don’t get why the password is not asked ?

    This mean whoever get my user access can changes files on /etc/ without knowledge of the sudo password ?

  • 🐧 nixCraft Mar 31, 2010 @ 12:21


    You must have used sudo earlier. It remembers the password for some time (see sudo man page for more info). Another possibility is – you may have configured sudo without the password.

  • Nic0 Mar 31, 2010 @ 12:43

    @Vivek Gite, My mistake, I did probably used sudo before. (and entry the password)
    I tried again, and it ask for the password this time. Sorry.

    Thanks for the tips anyway.

  • linuxnetzer Mar 31, 2010 @ 12:53

    that one bugged me long enough. Cheers!

  • kizzx2 Mar 31, 2010 @ 17:28

    This is very useful! Thanks!

  • Philippe Petrinko Apr 1, 2010 @ 20:56

    Nice – but – sudo on my PC is configured to ask my password for every sudo call.
    But then this tip fails, because I can see sudo requesting my password, waiting one second, then, as if I entered a wrong passwd, it fails, until three times, and I get rejected without beeing able to type my password in.
    So, will this tip only work if sudo is configured not to ask password?
    Did you test it?
    If so, do you know why sudo is getting an entry? I do not type anything, but it seems to get some input through the [:w !sudo tee %] command.
    Of course, I tried to type in my password – it failed.

  • 🐧 nixCraft Apr 2, 2010 @ 6:33


    Sudo is also configured here and I’ve no problem. What about passwd_timeout and timestamp_timeout?

  • Philippe Petrinko Apr 2, 2010 @ 8:39


    No, that is not related to sudo parameters.
    If found this: This tip works for [vi] or [vim],
    but I have got this problem only with [gvim] – which is odd but true.

  • 🐧 nixCraft Apr 4, 2010 @ 8:22


    I see we are talking about GUI here. Have you tried out gui version of sudo gksudo instead of sudo? Try it on dummy file as gksudo some time provides real weird results when combined with shell utilizes (may be steams are not connected but dunno).


  • Philippe Petrinko Apr 4, 2010 @ 8:37

    I just tried gksudo in place of sudo, it fails because :
    – I enter :w ! gksudo tee %
    – Then, I get a new line – no prompt – I try to enter my password, nothing happens,
    I quit by , and then file is overwritten, but emptied by the procedure!
    (also tried with gksudo -P)
    So, in a way – it works ;-) file is wiped… :-/
    That was a nice idea anyway!

  • Philippe Petrinko Apr 4, 2010 @ 8:38

    grrr Wordpress has eaten my words : I typed

    I quit by , and then file is overwritten,

  • Philippe Petrinko Apr 4, 2010 @ 8:40

    Shooot !!! I ***** dislike Wordpress text entry !

  • 🐧 nixCraft Apr 4, 2010 @ 13:24


    I’m out of ideas for gvim here and I guess it is related to GUI. Both stderr and stdout are terminal streams. And GUI version of gvim accept messages from user input devices (??), not from stdin so I guess you are getting empty file as a result. May be you need to patch gksudo to accept stderr or come with some sort of wrapper (we do this all the time with php-cgi and perl cgi fastcgi). Please update us if you find any other solution to your problem.

  • Bhaskar Chowdhury Apr 11, 2010 @ 13:50

    Nice tip..but unfortunately it doesn’t work for me. I have followed discussion here and implemented the same thing …oh forget to tell that I am on Gentoo.
    1)I have used sudo before run this command..(so that’s in history)
    2)say I have open /etc/ntp.conf and once I passed the recommendation like this
    :w !sudo tee %
    it asked for password(that’s fine..if the time elapsed)

    but says “Press enter to continue..”

    @ Vivek

    any idea??


    • 🐧 nixCraft Apr 12, 2010 @ 7:58

      No idea, check /var/log/secure (RHEL / CentOS) or /var/log/auth.log (Debian and friends) logs details about sudo command and failed attempts. This may provide additional help. I’ve used this many times under Debian and RHEL based servers.

  • Daniel Apr 11, 2010 @ 14:56

    This is neat. However, why not run Vi as root in the beginning? i.e.,

    $ sudo vi /etc/fstab

  • Shane Kerns Apr 11, 2010 @ 15:33

    How stupid can this post possibly get? If a username is already in sudo then he/she can just become root and edit a file.
    If a username is configured only to do certain things like edit config files then there should be be no problem in editing that file to begin with, just use “sudo su”.

    • Daniel Apr 12, 2010 @ 13:14

      Exactly, this is a good post because if you are vim’ing a file and have spent a lot of time and effort, and then realize you don’t have rights to :w the edits, then this is a perfect quick solution.

  • gregf Apr 11, 2010 @ 23:57

    @Shane shouldn’t be calling anyone stupid when your typing sudo su. Try reading the sudo man page. The purpose of the post was to show you how to edit a file, you don’t have permissions to, without closing your editor and opening it again within sudo.

  • Christian Apr 21, 2010 @ 11:05

    There is also this Plugin SudoEdit.vim available, which provides the commands :SudoWrite and :SudoRead and uses TabCompletion for filenames. You can configure it to use sudo or su or even ssh.

  • Anonymous Jun 22, 2010 @ 9:22

    this will work only the user is sudo user.

  • Anil Wable Jan 7, 2012 @ 7:39

    @ all,

    i need to configure insult para in sudo file after given correct para it doesn’t work for me any ideas…?
    para :- Defaults instults

    but same message shown after configure “Sorry, try again.”

  • Jakob Feb 20, 2012 @ 14:17

    :w !sudo tee %


    :w !sudo tee %
    Password:Sorry, try again.
    Sorry, try again.
    Sorry, try again.
    sudo: 3 incorrect password attempts

    shell returned 1
    Press ENTER or type command to continue

  • sa Aug 8, 2012 @ 13:30

    how do we disable this option in linux since there are chances for the users to edit the files

  • Noob Dec 19, 2014 @ 15:04

    Please help me! ANYONE !?!?!
    As you can see I’m a noob… please help me :D
    I logged in a ‘root’ etc but when I used this command ‘vi BLAHBLAH.conf’
    I can’t edit anything ;( why is this and how do I fix?

  • Brunch Feb 19, 2015 @ 9:39

    Wow! Kudos on your excellent hack!

  • Anderew Porter May 20, 2015 @ 7:59

    I think a nicer solution that doesn’t require piping the document through tee would be to write it to a temporary file and then sudo mv tmp % – more complex to type in but if you are mapping it as a command it can be as complex as needed.

  • JTEAS May 20, 2015 @ 11:52

    If you are using this method, constantly forgetting what user account you are using, you might not want to be editing a root owned file. Maybe. If you MUST create sudo rules, specify them. Telling a new Linux user/admin to use the admin group, and then allow ALL COMMANDS to ALL HOSTS? I simply have nothing nice to say about it. Instead, I would refer you to a book called “Sudo Mastery” by Michael W. Lucas, and wish you the best of luck.

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum