【发布时间】:2020-09-20 08:14:34
【问题描述】:
我正在关注https://lifehacker.com/add-a-handy-separator-between-commands-in-your-terminal-5840450,以便在 Linux 终端中的命令之间创建一个很好的分隔符。具体来说,CentOS 8。
我正在尝试修改脚本以输出运行该命令的用户的用户名。
Here 是我想出的。
# Fill with minuses
# (this is recalculated every time the prompt is shown in function prompt_command):
fill="--- "
reset_style='\[\033[00m\]'
if [ -z "$VIM" ];
then status_style=$reset_style'\[\033[0;90m\]' # gray color; use 0;37m for lighter color
else status_style=$reset_style'\[\033[0;90;107m\]'
fi
prompt_style=$reset_style
command_style=$reset_style'\[\033[1;29m\]' # bold black
# Prompt variable:
OLD_PS1="$PS1"
PS1="$status_style"'$fill $USER \t\n'"$prompt_style$OLD_PS1$command_style"
# Reset color for command output
# (this one is invoked every time before a command is executed):
trap 'echo -ne "\e[0m"' DEBUG
function prompt_command {
# create a $fill of all screen width minus the time string and a space and USER and a space:
let fillsize=${COLUMNS}-10-${#USER}
fill=""
while [ "$fillsize" -gt "0" ]
do
fill="-${fill}" # fill with underscores to work on
let fillsize=${fillsize}-1
done
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
bname=`basename "${PWD/$HOME/~}"`
echo -ne "\033]0;${bname}: ${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"
;;
*)
;;
esac
}
PROMPT_COMMAND=prompt_command
第 15 行在生成的内容中添加了“”和$USER。
第 25 行更改为包含一个额外的空格和变量 $USER 的长度
看起来就像我想要的那样。
但是,如果我以sudo 运行命令,我想更新代码以输出。
理想情况下,它会将名称更改为 root 或任何 root 用户名。
我尝试了几件事,主要是我尝试使用whoami,但这总是返回我的用户名而不是 root。
如果我运行 sudo whoami 我会得到 root 但不是来自脚本。
我也试过EUID没有骰子。
此时,我已使用 $USER 引用将代码保持在工作状态,但我愿意将其更改为所需的任何内容。
【问题讨论】:
-
@JohnKugelman 谢谢你,我会试试的。在网上搜索时,最接近我的问题被发布在这里,所以我想我会试一试。