How to add a line to a file which has only root write permission and to continue the script execution

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

up vote
8
down vote

favorite

1

I am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires root permission to write.

The code looks like this:

# some code
echo "add this line to the code" >> fileName
# some code

Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.

share|improve this question

    up vote
    8
    down vote

    favorite

    1

    I am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires root permission to write.

    The code looks like this:

    # some code
    echo "add this line to the code" >> fileName
    # some code
    

    Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.

    share|improve this question

      up vote
      8
      down vote

      favorite

      1

      up vote
      8
      down vote

      favorite

      1
      1

      I am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires root permission to write.

      The code looks like this:

      # some code
      echo "add this line to the code" >> fileName
      # some code
      

      Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.

      share|improve this question

      I am trying to learn bash scripting. I am working on a practical problem and at one point I need to add a line to a file which requires root permission to write.

      The code looks like this:

      # some code
      echo "add this line to the code" >> fileName
      # some code
      

      Is it possible to somehow make the script ask for the root password, validate the password, and on successful authentication modify the file? The script should then return to the user mode and continue the command execution.

      bash scripting io-redirection root

      share|improve this question

      share|improve this question

      share|improve this question

      share|improve this question

      edited May 4 ’12 at 22:57

      Gilles

      524k12610481578

      524k12610481578

      asked May 4 ’12 at 3:08

      Alex

      350159

      350159

          5 Answers
          5

          active

          oldest

          votes

          up vote
          10
          down vote

          accepted

          There’s a tip in the sudo man page which explains how to do something like this. Here’s my one-liner:

          #!/usr/bin/bash
          sudo sh -c "echo "add this line to the code" >> fileName"
          

          Obviously, you’ll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

          share|improve this answer

            up vote
            2
            down vote

            su is available on most unix systems and should work:

            su root -c 'echo "add this line to the code" >> fileName'
            

            share|improve this answer

            • Unlike with sudo, passwords don’t seem to get cached with su.
              – Ryne Everett
              Mar 22 ’15 at 22:47

            • @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
              – miracle173
              Mar 24 ’15 at 12:02

            up vote
            1
            down vote

            You could use tee with sudo:

            echo "add this line to the code" | sudo tee -a filename > /dev/null
            

            echo‘s output is redirected with | (pipe) to sudo tee.
            tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten.
            As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee‘s output to standard output.

            One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

            share|improve this answer

              up vote
              0
              down vote

              Try this
              This command is available on Unix and Linux.

              sudo sh -c "echo 'add this line to the code' >> fileName"

              share|improve this answer

                up vote
                -2
                down vote

                Would do the trick:

                ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
                

                share|improve this answer

                • Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                  – Adaephon
                  May 14 ’14 at 21:26

                • I think you will run into troubles with you double quotes
                  – miracle173
                  Mar 24 ’15 at 12:05

                Your Answer

                StackExchange.ready(function() {
                var channelOptions = {
                tags: “”.split(” “),
                id: “106”
                };
                initTagRenderer(“”.split(” “), “”.split(” “), channelOptions);

                StackExchange.using(“externalEditor”, function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using(“snippets”, function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: ‘answer’,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: “”,
                imageUploader: {
                brandingHtml: “Powered by u003ca class=”icon-imgur-white” href=”https://imgur.com/”u003eu003c/au003e”,
                contentPolicyHtml: “User contributions licensed under u003ca href=”https://creativecommons.org/licenses/by-sa/3.0/”u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href=”https://stackoverflow.com/legal/content-policy”u003e(content policy)u003c/au003e”,
                allowUrls: true
                },
                onDemand: true,
                discardSelector: “.discard-answer”
                ,immediatelyShowMarkdownHelp:true
                });

                }
                });

                draft saved
                draft discarded

                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2funix.stackexchange.com%2fquestions%2f37875%2fhow-to-add-a-line-to-a-file-which-has-only-root-write-permission-and-to-continue%23new-answer’, ‘question_page’);
                }
                );

                Post as a guest

                Required, but never shown

                5 Answers
                5

                active

                oldest

                votes

                5 Answers
                5

                active

                oldest

                votes

                active

                oldest

                votes

                active

                oldest

                votes

                up vote
                10
                down vote

                accepted

                There’s a tip in the sudo man page which explains how to do something like this. Here’s my one-liner:

                #!/usr/bin/bash
                sudo sh -c "echo "add this line to the code" >> fileName"
                

                Obviously, you’ll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

                share|improve this answer

                  up vote
                  10
                  down vote

                  accepted

                  There’s a tip in the sudo man page which explains how to do something like this. Here’s my one-liner:

                  #!/usr/bin/bash
                  sudo sh -c "echo "add this line to the code" >> fileName"
                  

                  Obviously, you’ll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

                  share|improve this answer

                    up vote
                    10
                    down vote

                    accepted

                    up vote
                    10
                    down vote

                    accepted

                    There’s a tip in the sudo man page which explains how to do something like this. Here’s my one-liner:

                    #!/usr/bin/bash
                    sudo sh -c "echo "add this line to the code" >> fileName"
                    

                    Obviously, you’ll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

                    share|improve this answer

                    There’s a tip in the sudo man page which explains how to do something like this. Here’s my one-liner:

                    #!/usr/bin/bash
                    sudo sh -c "echo "add this line to the code" >> fileName"
                    

                    Obviously, you’ll first have to set up your user to have sudo privileges. The sh shell is used because of the redirection to the root-owned file. I also had to escape the quotes used for the echo command.

                    share|improve this answer

                    share|improve this answer

                    share|improve this answer

                    answered May 4 ’12 at 4:31

                    SigueSigueBen

                    882813

                    882813

                        up vote
                        2
                        down vote

                        su is available on most unix systems and should work:

                        su root -c 'echo "add this line to the code" >> fileName'
                        

                        share|improve this answer

                        • Unlike with sudo, passwords don’t seem to get cached with su.
                          – Ryne Everett
                          Mar 22 ’15 at 22:47

                        • @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                          – miracle173
                          Mar 24 ’15 at 12:02

                        up vote
                        2
                        down vote

                        su is available on most unix systems and should work:

                        su root -c 'echo "add this line to the code" >> fileName'
                        

                        share|improve this answer

                        • Unlike with sudo, passwords don’t seem to get cached with su.
                          – Ryne Everett
                          Mar 22 ’15 at 22:47

                        • @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                          – miracle173
                          Mar 24 ’15 at 12:02

                        up vote
                        2
                        down vote

                        up vote
                        2
                        down vote

                        su is available on most unix systems and should work:

                        su root -c 'echo "add this line to the code" >> fileName'
                        

                        share|improve this answer

                        su is available on most unix systems and should work:

                        su root -c 'echo "add this line to the code" >> fileName'
                        

                        share|improve this answer

                        share|improve this answer

                        share|improve this answer

                        answered May 4 ’12 at 5:30

                        miracle173

                        40229

                        40229

                        • Unlike with sudo, passwords don’t seem to get cached with su.
                          – Ryne Everett
                          Mar 22 ’15 at 22:47

                        • @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                          – miracle173
                          Mar 24 ’15 at 12:02

                        • Unlike with sudo, passwords don’t seem to get cached with su.
                          – Ryne Everett
                          Mar 22 ’15 at 22:47

                        • @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                          – miracle173
                          Mar 24 ’15 at 12:02

                        Unlike with sudo, passwords don’t seem to get cached with su.
                        – Ryne Everett
                        Mar 22 ’15 at 22:47

                        Unlike with sudo, passwords don’t seem to get cached with su.
                        – Ryne Everett
                        Mar 22 ’15 at 22:47

                        @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                        – miracle173
                        Mar 24 ’15 at 12:02

                        @Ryne Everett: I am not familiar with sudo. But the behaviour of ‘su’ is actually as needed by the script of the OP. Most of the time I use ‘su’ the other way round: changing from root to another user. In this case no password is needed ast all.
                        – miracle173
                        Mar 24 ’15 at 12:02

                        up vote
                        1
                        down vote

                        You could use tee with sudo:

                        echo "add this line to the code" | sudo tee -a filename > /dev/null
                        

                        echo‘s output is redirected with | (pipe) to sudo tee.
                        tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten.
                        As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee‘s output to standard output.

                        One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

                        share|improve this answer

                          up vote
                          1
                          down vote

                          You could use tee with sudo:

                          echo "add this line to the code" | sudo tee -a filename > /dev/null
                          

                          echo‘s output is redirected with | (pipe) to sudo tee.
                          tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten.
                          As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee‘s output to standard output.

                          One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

                          share|improve this answer

                            up vote
                            1
                            down vote

                            up vote
                            1
                            down vote

                            You could use tee with sudo:

                            echo "add this line to the code" | sudo tee -a filename > /dev/null
                            

                            echo‘s output is redirected with | (pipe) to sudo tee.
                            tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten.
                            As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee‘s output to standard output.

                            One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

                            share|improve this answer

                            You could use tee with sudo:

                            echo "add this line to the code" | sudo tee -a filename > /dev/null
                            

                            echo‘s output is redirected with | (pipe) to sudo tee.
                            tee reads from standard input and writes to standard output any given file, in this case filename. -a (or --append) makes tee append to files, without it the files would be overwritten.
                            As tee is run with sudo it opens files with root-permissions. Finally, > /dev/null suppresses tee‘s output to standard output.

                            One advantage of using tee instead of just starting the whole command including redirection with su -c or sudo sh -c is, that you do not have to change the quoting of the initial command in any way (Quoting lines already containing quotes can get quite ugly at times).

                            share|improve this answer

                            share|improve this answer

                            share|improve this answer

                            answered May 17 ’14 at 14:02

                            Adaephon

                            2,63311020

                            2,63311020

                                up vote
                                0
                                down vote

                                Try this
                                This command is available on Unix and Linux.

                                sudo sh -c "echo 'add this line to the code' >> fileName"

                                share|improve this answer

                                  up vote
                                  0
                                  down vote

                                  Try this
                                  This command is available on Unix and Linux.

                                  sudo sh -c "echo 'add this line to the code' >> fileName"

                                  share|improve this answer

                                    up vote
                                    0
                                    down vote

                                    up vote
                                    0
                                    down vote

                                    Try this
                                    This command is available on Unix and Linux.

                                    sudo sh -c "echo 'add this line to the code' >> fileName"

                                    share|improve this answer

                                    Try this
                                    This command is available on Unix and Linux.

                                    sudo sh -c "echo 'add this line to the code' >> fileName"

                                    share|improve this answer

                                    share|improve this answer

                                    share|improve this answer

                                    answered Nov 29 at 5:31

                                    JongYoung

                                    1

                                    1

                                        up vote
                                        -2
                                        down vote

                                        Would do the trick:

                                        ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
                                        

                                        share|improve this answer

                                        • Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                          – Adaephon
                                          May 14 ’14 at 21:26

                                        • I think you will run into troubles with you double quotes
                                          – miracle173
                                          Mar 24 ’15 at 12:05

                                        up vote
                                        -2
                                        down vote

                                        Would do the trick:

                                        ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
                                        

                                        share|improve this answer

                                        • Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                          – Adaephon
                                          May 14 ’14 at 21:26

                                        • I think you will run into troubles with you double quotes
                                          – miracle173
                                          Mar 24 ’15 at 12:05

                                        up vote
                                        -2
                                        down vote

                                        up vote
                                        -2
                                        down vote

                                        Would do the trick:

                                        ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
                                        

                                        share|improve this answer

                                        Would do the trick:

                                        ssh host "sudo su root -c 'echo "add this line to the code" >> /etc/hosts'"
                                        

                                        share|improve this answer

                                        share|improve this answer

                                        share|improve this answer

                                        edited May 14 ’14 at 19:35

                                        Ramesh

                                        23k32101180

                                        23k32101180

                                        answered May 14 ’14 at 19:29

                                        user1934677

                                        1

                                        1

                                        • Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                          – Adaephon
                                          May 14 ’14 at 21:26

                                        • I think you will run into troubles with you double quotes
                                          – miracle173
                                          Mar 24 ’15 at 12:05

                                        • Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                          – Adaephon
                                          May 14 ’14 at 21:26

                                        • I think you will run into troubles with you double quotes
                                          – miracle173
                                          Mar 24 ’15 at 12:05

                                        Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                        – Adaephon
                                        May 14 ’14 at 21:26

                                        Why ssh? You do not need su with sudo and neither do you need to specify root as it is the default. All in all, a bit more explanations would be nice as the OP wanted to learn something and not just a problem solved.
                                        – Adaephon
                                        May 14 ’14 at 21:26

                                        I think you will run into troubles with you double quotes
                                        – miracle173
                                        Mar 24 ’15 at 12:05

                                        I think you will run into troubles with you double quotes
                                        – miracle173
                                        Mar 24 ’15 at 12:05

                                        draft saved
                                        draft discarded

                                        Thanks for contributing an answer to Unix & Linux Stack Exchange!

                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid

                                        • Asking for help, clarification, or responding to other answers.
                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.

                                        Some of your past answers have not been well-received, and you’re in danger of being blocked from answering.

                                        Please pay close attention to the following guidance:

                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid

                                        • Asking for help, clarification, or responding to other answers.
                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.

                                        draft saved

                                        draft discarded

                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin(‘.new-post-login’, ‘https%3a%2f%2funix.stackexchange.com%2fquestions%2f37875%2fhow-to-add-a-line-to-a-file-which-has-only-root-write-permission-and-to-continue%23new-answer’, ‘question_page’);
                                        }
                                        );

                                        Post as a guest

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Required, but never shown

                                        Related Post

                                        Leave a Reply

                                        Your email address will not be published. Required fields are marked *