![](/img/trans.png)
[英]shell script executes as root when it should execute as current logged in user
[英]After logged as root it wont execute in ubuntu linux shell script
在这里,我创建了一个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
su
启动了一个root shell。 除非您退出shell(通过exit
),否则该命令实际上不会将控制权返回给您的脚本。 按设计工作。
如果要执行特定命令 ,而不是打开shell,请像这样使用它:
su -c echo "User logged as root"
或者,甚至更好,
sudo echo "User logged as root"
无论哪种方式,你都知道,一旦你的脚本结束,你将回到你开始的地方,即你不会通过启动脚本获得root shell? (因为脚本本身也在子shell中运行。)
你忘记了"
在你的情况下根深蒂固
#!/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
我需要的是,只有在用户输入SU的密码后才运行命令,只需将程序拆分为两个bash文件
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`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.