使用sudo运行时在shell脚本中获取$ USER? [英] Getting $USER inside shell script when running with sudo?

查看:52
本文介绍了使用sudo运行时在shell脚本中获取$ USER?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用 sudo 运行 shell 脚本,我如何获得正确的 $USER ?

How do I get the correct $USER if I run a shell script with sudo ?

我在 Mac 安装包中将它们作为安装后脚本运行,在那里它们会被自动 sudo-ed,但我需要使用用户名做一些事情.

I run them as postinstall scripts in a Mac install package, where they are being sudo-ed automatically, but I need to do stuff with the username.

不过,$HOME 是正确的.不优雅的方法是从主路径中提取名称,但我想知道是否有一种自然的方法可以做到这一点.

$HOME is correct, though. The inelegant method would be to extract the name from the home path, but I wonder if there is a natural way to do this.

我无法影响脚本的调用方式,因为它是安装程序内部的自动调用.

I can't influence the way the scripts are being called, as it's an automatic call inside the installer.

推荐答案

在我的系统上,变量 $SUDO_USER 被设置为调用者的用户名.

On my system the variable $SUDO_USER is set to the caller's user name.

您不应直接从 ${HOME} 变量中提取用户名.它正在配置而不是计算.要提取用户名,您可以查看 /etc/passwd 文件,但这非常依赖于系统,例如有时您必须查看 LDAP 目录或条目通过 NIS 传播...

You shouldn't extract the username from the ${HOME} variable directly. It's being configured and not calculated. To Extract the username you could take a look into /etc/passwd file, but this is very system dependent, e.g. sometimes you have to look into a LDAP directory or the entries are propagated through NIS ...

这篇关于使用sudo运行时在shell脚本中获取$ USER?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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