<p>Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type</p>

<pre><code>sudo vi filename
</code></pre>

<p>Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.</p>

[{'answer_id': 1006, 'author': 'Ryan Fox', 'author_id': 55, 'author_profile': 'https://Stackoverflow.com/users/55', 'pm_score': 1, 'selected': False, 'text': '<p>A quick Google seems to give this advice:</p>\n\n<ol>\n<li>Don\'t try to edit if it\'s read-only.</li>\n<li>You might be able to change the permissions on the file. (Whether or not it will let you save is up to experimentation.)</li>\n<li>If you still edited anyway, save to a temporary file and then move it.</li>\n</ol>\n\n<p><a href="http://ubuntuforums.org/showthread.php?t=782136" rel="nofollow noreferrer">http://ubuntuforums.org/showthread.php?t=782136</a></p>\n'}, {'answer_id': 1012, 'author': 'C. K. Young', 'author_id': 13, 'author_profile': 'https://Stackoverflow.com/users/13', 'pm_score': 3, 'selected': False, 'text': "<p>Ryan's advice is generally good, however, if following step 3, don't move the temporary file; it'll have the wrong ownership and permissions. Instead, <code>sudoedit</code> the correct file and read in the contents (using <code>:r</code> or the like) of the temporary file.</p>\n\n<p>If following step 2, use <code>:w!</code> to force the file to be written.</p>\n"}, {'answer_id': 1065, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 5, 'selected': False, 'text': "<p>In general, you can't change the effective user id of the vi process, but you can do this:</p>\n\n<pre><code>:w !sudo tee myfile\n</code></pre>\n"}, {'answer_id': 2930, 'author': 'num1', 'author_id': 306, 'author_profile': 'https://Stackoverflow.com/users/306', 'pm_score': -1, 'selected': False, 'text': "<p>A quick hack you can consider is doing a chmod on the file you're editing, save with vim, and then chmod back to what the file was originally.</p>\n\n<pre><code>ls -l test.file (to see the permissions of the file)\nchmod 777 test.file\n[This is where you save in vim]\nchmod xxx test.file (restore the permissions you found in the first step)\n</code></pre>\n\n<p>Of course I don't recommend this approach in a system where you're worried about security, as for a few seconds anyone can read/change the file without you realizing.</p>\n"}, {'answer_id': 9113, 'author': 'dbr', 'author_id': 745, 'author_profile': 'https://Stackoverflow.com/users/745', 'pm_score': 2, 'selected': False, 'text': '<p>When you go into insert mode on a file you need sudo access to edit, you get a status message saying</p>\n\n<pre><code>-- INSERT -- W10: Warning: Changing a readonly file\n</code></pre>\n\n<p>If I miss that, generally I do</p>\n\n<pre><code>:w ~/edited_blah.tmp\n:q\n</code></pre>\n\n<p>..then..</p>\n\n<pre><code>sudo "cat edited_blah.tmp &gt; /etc/blah"\n</code></pre>\n\n<p>..or..</p>\n\n<pre><code>sudo mv edited_blah.tmp /etc/blah\n</code></pre>\n\n<p>There\'s probably a less roundabout way to do it, but it works.</p>\n'}, {'answer_id': 37042, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 9, 'selected': True, 'text': '<p><code>%</code> is replaced with the current file name, thus you can use:</p>\n\n<pre><code>:w !sudo tee %\n</code></pre>\n\n<p>(<code>vim</code> will detect that the file has been changed and ask whether you want to it to be reloaded. Say yes by choosing <code>[L]</code> rather than OK.)</p>\n\n<p>As a shortcut, you can define your own command. Put the following in your <code>.vimrc</code>:</p>\n\n<pre><code>command W w !sudo tee % &gt;/dev/null\n</code></pre>\n\n<p>With the above you can type <code>:W&lt;Enter&gt;</code> to save the file. Since I wrote this, I have found a nicer way (in my opinion) to do this:</p>\n\n<pre><code>cmap w!! w !sudo tee &gt;/dev/null %\n</code></pre>\n\n<p>This way you can type <code>:w!!</code> and it will be expanded to the full command line, leaving the cursor at the end, so you can replace the <code>%</code> with a file name of your own, if you like.</p>\n'}, {'answer_id': 125383, 'author': 'ephemient', 'author_id': 20713, 'author_profile': 'https://Stackoverflow.com/users/20713', 'pm_score': 4, 'selected': False, 'text': '<p>If you\'re using <a href="http://www.vim.org/" rel="nofollow noreferrer">Vim</a>, there is a script available named <a href="http://www.vim.org/scripts/script.php?script_id=729" rel="nofollow noreferrer">sudo.vim</a>.  If you find that you\'ve opened a file that you need root access to read, type<pre>:e sudo:%</pre>Vim replaces the % with the name of the current file, and <code>sudo:</code> instructs the sudo.vim script to take over for reading and writing.</p>\n'}, {'answer_id': 662081, 'author': 'pisswillis', 'author_id': 78414, 'author_profile': 'https://Stackoverflow.com/users/78414', 'pm_score': 0, 'selected': False, 'text': "<p>I have this in my ~/.bashrc:</p>\n\n<pre><code>alias svim='sudo vim'\n</code></pre>\n\n<p>Now whenever I need to edit a config file I just open it with svim.</p>\n"}, {'answer_id': 2163726, 'author': 'James Snyder', 'author_id': 105950, 'author_profile': 'https://Stackoverflow.com/users/105950', 'pm_score': 1, 'selected': False, 'text': '<p>Here\'s another one that has appeared since this question was answered, a plugin called SudoEdit which provides SudoRead and SudoWrite functions, which will by default try to use sudo first and su if that fails: <a href="http://www.vim.org/scripts/script.php?script_id=2709" rel="nofollow noreferrer">http://www.vim.org/scripts/script.php?script_id=2709</a></p>\n'}, {'answer_id': 12870763, 'author': 'Zenexer', 'author_id': 1188377, 'author_profile': 'https://Stackoverflow.com/users/1188377', 'pm_score': 4, 'selected': False, 'text': '<h1>Common Caveats</h1>\n\n<p>The most common method of getting around the read-only file problem is to open a pipe to current file as the super-user using an implementation of <code>sudo tee</code>.  However, all of the most popular solutions that I have found around the Internet have a combination of a several potential caveats:</p>\n\n<ul>\n<li>The entire file gets written to the terminal, as well as the file.  This can be slow for large files, especially over slow network connections.</li>\n<li>The file loses its modes and similar attributes.</li>\n<li>File paths with unusual characters or spaces might not be handled correctly.</li>\n</ul>\n\n<h1>Solutions</h1>\n\n<p>To get around all of these issues, you can use the following command:</p>\n\n<pre><code>" On POSIX (Linux/Mac/BSD):\n:silent execute \'write !sudo tee \' . shellescape(@%, 1) . \' &gt;/dev/null\'\n\n" Depending on the implementation, you might need this on Windows:\n:silent execute \'write !sudo tee \' . shellescape(@%, 1) . \' &gt;NUL\'\n</code></pre>\n\n<p>These can be shortened, respectfully:</p>\n\n<pre><code>:sil exec \'w !sudo tee \' . shellescape(@%, 1) . \' &gt;/dev/null\'\n:sil exec \'w !sudo tee \' . shellescape(@%, 1) . \' &gt;NUL\'\n</code></pre>\n\n<h1>Explanation</h1>\n\n<p><code>:</code> begins the command; you will need to type this character in normal mode to start entering a command.  It should be omitted in scripts.</p>\n\n<p><code>sil[ent]</code> suppresses output from the command.  In this case, we want to stop the <code>Press any key to continue</code>-like prompt that appears after running the <code>:!</code> command.</p>\n\n<p><code>exec[ute]</code> executes a string as a command.  We can\'t just run <code>:write</code> because it won\'t process the necessary function call.</p>\n\n<p><code>!</code> represents the <code>:!</code> command: the only command that <code>:write</code> accepts.  Normally, <code>:write</code> accepts a file path to which to write.  <code>:!</code> on its own runs a command in a shell (for example, using <code>bash -c</code>).  With <code>:write</code>, it will run the command in the shell, and then write the entire file to <code>stdin</code>.</p>\n\n<p><code>sudo</code> should be obvious, since that\'s why you\'re here.  Run the command as the super-user.  There\'s plenty of information around the \'net about how that works.</p>\n\n<p><code>tee</code> pipes <code>stdin</code> to the given file.  <code>:write</code> will write to <code>stdin</code>, then the super-user <code>tee</code> will receive the file contents and write the file.  It won\'t create a new file--just overwrite the contents--so file modes and attributes will be preserved.</p>\n\n<p><code>shellescape()</code> escapes special characters in the given file path as appropriate for the current shell.  With just one parameter, it would typically just enclose the path in quotes as necessary.  Since we\'re sending to a full shell command line, we\'ll want to pass a non-zero value as the second argument to enable backslash-escaping of other special characters that might otherwise trip up the shell.</p>\n\n<p><code>@%</code> reads the contents of the <code>%</code> register, which contains the current buffer\'s file name.  It\'s not necessarily an absolute path, so ensure that you haven\'t changed the current directory.  In some solutions, you will see the commercial-at symbol omitted.  Depending on the location, <code>%</code> is a valid expression, and has the same effect as reading the <code>%</code> register.  Nested inside another expression the shortcut is generally disallowed, however: such as in this case.</p>\n\n<p><code>&gt;NUL</code> and <code>&gt;/dev/null</code> redirect <code>stdout</code> to the platform\'s null device.  Even though we\'ve silenced the command, we don\'t want all of the overhead associated with piping <code>stdin</code> back to vim--best to dump it as early as possible.  <code>NUL</code> is the null device on DOS, MS-DOS, and Windows, not a valid file.  As of Windows 8 redirections to NUL don\'t result in a file named NUL being written.  Try creating a file on your desktop named NUL, with or without a file extension: you will be unable to do so.  (There are several other device names in Windows that might be worth getting to know.)</p>\n\n<h1>~/.vimrc</h1>\n\n<h2>Platform-Dependent</h2>\n\n<p>Of course, you still don\'t want to memorize those and type them out each time.  It\'s much easier to map the appropriate command to a simpler user command.  To do this on POSIX, you could add the following line to your <code>~/.vimrc</code> file, creating it if it doesn\'t already exist:</p>\n\n<pre><code>command W silent execute \'write !sudo tee \' . shellescape(@%, 1) . \' &gt;/dev/null\'\n</code></pre>\n\n<p>This will allow you to type the :W (case-sensitive) command to write the current file with super-user permissions--much easier.</p>\n\n<h2>Platform-Independent</h2>\n\n<p>I use a platform-independent <code>~/.vimrc</code> file that synchronizes across computers, so I added multi-platform functionality to mine.  Here\'s a <code>~/.vimrc</code> with only the relevant settings:</p>\n\n<pre><code>#!vim\n" Use za (not a command; the keys) in normal mode to toggle a fold.\n" META_COMMENT Modeline Definition: {{{1\n" vim: ts=4 sw=4 sr sts=4 fdm=marker ff=unix fenc=utf-8\n"   ts:     Actual tab character stops.\n"   sw:     Indentation commands shift by this much.\n"   sr:     Round existing indentation when using shift commands.\n"   sts:    Virtual tab stops while using tab key.\n"   fdm:    Folds are manually defined in file syntax.\n"   ff:     Line endings should always be &lt;NL&gt; (line feed #09).\n"   fenc:   Should always be UTF-8; #! must be first bytes, so no BOM.\n\n\n" General Commands: User Ex commands. {{{1\n    command W call WriteAsSuperUser(@%)         " Write file as super-user.\n\n\n" Helper Functions: Used by user Ex commands. {{{1\n    function GetNullDevice() " Gets the path to the null device. {{{2\n        if filewritable(\'/dev/null\')\n            return \'/dev/null\'\n        else\n            return \'NUL\'\n        endif\n    endfunction\n\n    function WriteAsSuperUser(file) " Write buffer to a:file as the super user (on POSIX, root). {{{2\n        exec \'%write !sudo tee \' . shellescape(a:file, 1) . \' &gt;\' . GetNullDevice()\n    endfunction\n\n\n" }}}1\n" EOF\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/1005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85/']