支持 Ubuntu 25 等 systemd 不再提供 utmp 的情景下获取当前用户名

Signed-off-by: shenmo <jifengshenmo@outlook.com>
This commit is contained in:
2025-04-18 15:01:44 +00:00
committed by Gitee
parent 05e00b41f9
commit 26dcf96d87
2 changed files with 15 additions and 2 deletions

View File

@@ -22,8 +22,20 @@ fi
HERE="$(dirname $(realpath $0))"
function get_current_user() {
# 优先通过 who 命令获取用户
local user
user=$(who | awk '{print $1}' | head -n 1 2>/dev/null)
non_root_user=$(who | awk '{print $1}' | head -n 1)
# 如果 who 无输出,则通过 loginctl 获取
if [[ -z "$user" ]]; then
user=$(loginctl list-sessions --no-legend 2>/dev/null | awk '{print $3}' | head -n 1)
fi
# 返回最终结果(可能为空)
echo "${user}"
}
non_root_user=$(get_current_user)
uid=$(id -u $non_root_user)
function bookworm-run(){