0

在这里,我创建了一个 linux shell 脚本来执行一个程序来回显“用户以 root 身份登录”。但它不会显示任何东西。如果我给出“退出”,那么它将显示“用户以 root 身份登录”。请帮我解决这个问题。

#!/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
4

3 回答 3

2

启动一个根su外壳。exit除非您退出 shell(通过),否则该命令实际上不会将控制权返回给您的脚本。按设计工作。

如果您想执行特定命令,而不是打开 shell,请像这样使用它:

su -c echo "User logged as root"

或者,甚至更好,

sudo echo "User logged as root"

无论哪种方式,您知道,一旦您的脚本结束,您将回到您开始的地方,即您不会通过启动脚本获得root shell?(因为脚本本身也在子 shell 中运行。)

于 2013-10-31T10:38:26.873 回答
0

你忘记了"你的情况下的根

#!/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
于 2013-10-31T10:39:12.977 回答
0

我需要的是,只有在用户输入 SU 的密码后才能运行命令,只需将程序拆分为两个 bash 文件

1 主.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 回声文件.sh

echo "user logged as root";
echo `whoami`
于 2013-10-31T11:43:42.360 回答