Arjun Pokkattu
Arjun Pokkattu

Reputation: 137

After logged as root it wont execute in ubuntu linux shell script

Here I created a linux shell script to execute a program to echo "User logged as root". But it wont show anything. if I give 'exit' then it will show "user logged as root". Please help me to solve this issue.

#!/bin/bash 
logged_user=`whoami`
if [ $logged_user != root ]
    then echo "You are not logged as root!"
    echo "Enter root password if root password is set"
    su                                #here it will ask to enter root password
    echo "user logged as root"        #this line is not working...  

fi

Upvotes: 0

Views: 140

Answers (3)

DevSolar
DevSolar

Reputation: 70263

The su starts a root shell. The command does not actually return control to your script unless you exit the shell (via exit). Works as designed.

If you want to have a specific command executed, instead of opening a shell, use it like this:

su -c echo "User logged as root"

or, even better,

sudo echo "User logged as root"

Either way, you are aware that, once your script ends, you will be back where you started, i.e. you will not get a root shell through starting a script? (Because the script itself runs in a subshell as well.)

Upvotes: 2

Arjun Pokkattu
Arjun Pokkattu

Reputation: 137

What I need is, to run commands only after the user inputs the password for SU, just split the program into two bash files

1 main.sh

#!/bin/bash 
logged_user=`whoami`
if [ $logged_user != root ]
    then echo "You are not logged as root!"
    echo "Enter root password if root password is set"
    su root echo_file.sh    #here it call echo_file.sh as root user    


fi

2 echo_file.sh

echo "user logged as root";
echo `whoami`

Upvotes: 0

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You forgot the " around root in your condition

#!/bin/bash 
logged_user=`whoami`
if [ $logged_user != "root" ]
    then echo "You are not logged as root!"
    echo "Enter root password if root password is set"
    su                                #here it will ask to enter root password
    echo "user logged as root"        #this line is not working...  

fi

Upvotes: 0

Related Questions