为什么我不能在shell脚本中使用'sudo su'?如何使Shell脚本自动使用sudo运行 [英] Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically

查看:1880
本文介绍了为什么我不能在shell脚本中使用'sudo su'?如何使Shell脚本自动使用sudo运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot figure out what's wrong with this. When I run it in terminal and enter password, nothing happens, but if I run every command separately in terminal, it works. Thank you!

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

推荐答案

命令sudo su启动交互式根shell,但不会将当前shell转换为根shell.

Command sudo su starts an interactive root shell, but it will not convert the current shell into a root one.

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

The idiom to do what you want is something along the lines of this (thanks to @CharlesDuffy for the extra carefulness):

#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

The idea is to check whether the current user is root, and if not, re-run the same command with su

这篇关于为什么我不能在shell脚本中使用'sudo su'?如何使Shell脚本自动使用sudo运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆