How to save a file in Vim / Vi without Root Permission with sudo on Linux Cloud Servers

2020-06-03 By Ryan 29164 Views linux sudo
15 reviews

On a Linux system, vim and vi are the most popular text editors. We can edit the content of the files and able save it using vi/vim editor.

By default the server configuration files are owned by the root user, hence the normal user can not write the changes due to insufficient Permission.


This article will guide you to the basic commands about how to save a file after writing or modifying its content without Root Permission using sudo option.


  1. Steps to edit the file /etc/hosts as a normal user.

    # vi /etc/hosts
    

    sudosave1

    After making some changes (E.g Adding a new entry) in the file, save it by typing the following normal command which you can see that vim/vi CANNOT open the file due to the permission. :

    :w!
    

    and then, Enter.

    sudosave2

    sudosave3

  2. Now you try to save the file by followingpressing,

    :w !sudo tee %
    

    :w – Write a file

    !sudo – Call shell with sudo command

    tee – The output of write command redirected using tee

    % - Indicate the Current filename. Here it is /etc/hosts

    And then, Enter.

    sudosave4

    sudosave5

  3. Enter the password of the logged-in user and then Enter.

    sudosave6

  4. Press L to load changes in vim itself.

  5. Now open the file again to see the changes.

    # cat /etc/hosts
    

    sudosave7


Related Tutorials

What do you think about this article?

Rate this article
LayerStack Promotion
Need assistance?

Try this guide to receive free bundled services at signup on a new free account.

Sign Up

Your Feedback Is Important

We hope you’ll give the new products and updates a try. If you have an idea for improving our products or want to vote on other user ideas so they get prioritized, please submit your feedback on our Community platform. And if you have any questions, please feel free to ask in the Community or contact our Technical Support team.