1

I am new in shell.

I'am writing a very basic script:

#!/bin/bash
example()
{

    echo "Code that don't need sudo."
    sudo -s 
    echo "Code that need sudo"
 }

example

After running this script i expect :

  1. prompt Code that don't need sudo.

  2. shell ask me password

  3. if the password is OK prompt Code that need sudo.

But after typing the good password the prompt Code that need sudo. does not appear why and how to fix it ?

1
3

That's because sudo -s starts a root shell, and that's where you find yourself after entering the password. If you then exit the shell, you will see the Code that need sudo:

$ foo.sh
Code that don't need sudo.
[sudo] password for terdon: 
[root@tpad terdon]# exit
Code that need sudo

In general, in all scripts, when you tell it to run a command, the script will only continue executing after the command has finished. So, when your script launched sudo -s, it waited for that to finish before continuing. That's why the text was printed after I ran exit (or pressed ctrl + D).

3

-s without a command runs an interactive shell, so you would no longer be in the same shell as the script.

See man sudo for details.

This should work though:

#!/bin/bash
example()
{

    echo "Code that don't need sudo."
    sudo -s echo "Code that need sudo"
 }

example
1
  • 3
    Note that there's hardly ever a good reason to use sudo -s some command instead of sudo some command. With sudo -s, sudo tries to quote the arguments properly to construct a shell command line that will eventually cause the shell to call some with some and command as argument, but it can't do that properly and even with sh or bash, does it wrong in a few corner cases (can even be tricked to run commands that were not intended). Mar 2 '17 at 21:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.