小编典典

为什么我不能在shell脚本中使用'sudo su'?如何使Shell脚本自动使用sudo运行

linux

我无法弄清楚这是怎么回事。当我在终端中运行它并输入密码时,什么也没发生,但是如果我在终端中单独运行每个命令,它就可以工作。谢谢!

#!/bin/bash

sudo su;
mkdir /opt/D3GO/;
cp `pwd`/D3GO /opt/D3GO/;
cp `pwd`/D3GO.png /opt/D3GO/;
cp `pwd`/D3GO.desktop /usr/share/applications/;
chmod +x /opt/D3GO/D3GO

阅读 1503

收藏
2020-06-07

共1个答案

小编典典

Command sudo su启动一个交互式根外壳程序,但不会将当前外壳程序转换为根外壳程序。

做您想要的事情的成语与此类似(感谢@CharlesDuffy的额外注意):

#check for root
UID=$(id -u)
if [ x$UID != x0 ] 
then
    #Beware of how you compose the command
    printf -v cmd_str '%q ' "$0" "$@"
    exec sudo su -c "$cmd_str"
fi

#I am root
mkdir /opt/D3GO/
#and the rest of your commands

这个想法是检查当前用户是否是root用户,如果不是,请使用以下命令重新运行同一命令 su

2020-06-07