8 configuration command-line bash bashrc
我已按照此处和此处提供的操作方法链接中的说明进行操作。但是似乎没有任何地方说明我如何更改不同部分的颜色,因为目前我将其设置为:
PS1='${debian_chroot:+($debian_chroot)}[\t] \u@\h:\w\$ '
Run Code Online (Sandbox Code Playgroud)
但是文字还是全白的,我怎么可能把时间的数字变成绿色,而我的用户名和计算机名变成蓝色?我正在运行 Ubuntu GNOME 15.04。
mch*_*hid 12
首先,打开你的 ~/.bashrc 文件并启用颜色提示:
nano ~/.bashrc
Run Code Online (Sandbox Code Playgroud)
取消注释然后行 #force_color_prompt=yes
然后,直接在线下改PS1线if [ "$color_prompt" = yes ]; then
到:
PS1='${debian_chroot:+($debian_chroot)}\[\033[00;32m\][\t] \[\033[01;34m\]\u@\h:\w\$ '
Run Code Online (Sandbox Code Playgroud)
如您所见,01:34m 是浅蓝色,00:32m 是绿色。浅绿色将是 01:32m 而不是 00:32m。
按CTRL+o然后按ENTER保存文件。按CTRL+x退出纳米。
然后,运行以下命令通过“采购”您的 bashrc 文件来应用更改:
. ~/.bashrc
Run Code Online (Sandbox Code Playgroud)
这些更改现在应该适用于您用户下的每个新打开的终端。
Ter*_*nce 10
这是我和我的一个朋友一直在研究的一个。当您是普通用户时,它会显示一条灰色虚线,然后如果您以 root 用户身份运行命令,则虚线和文本都会变为红色。
在您的.bashrc
文件中,将以下代码添加到文件底部:
if [ -f "$HOME/.bash_ps1" ]; then
. "$HOME/.bash_ps1"
fi
Run Code Online (Sandbox Code Playgroud)
编辑:另外,也将它添加到底部/root/.bashrc
。这是为了如果您root
通过发出命令切换到用户sudo su -
。(其余的编辑在代码下面继续)
然后将此代码的其余部分复制并粘贴到名为的新文件中 /home/<username>/.bash_ps1
# Fill with minuses
# (this is recalculated every time the prompt is shown in function prompt_command):
fill="--- "
reset_style='\[\033[00m\]'
# determine if root or not
a=$(id|awk -F\( '{print $1}')
if [ "$a" = "uid=0" ]
then
# for root
status_style=$reset_style'\[\033[1;31m\]' # bold red; use 0;37m for lighter color
command_style=$reset_style'\[\033[1;31m\]' # bold red
else
# for other users
status_style=$reset_style'\[\033[0;90m\]' # gray color; use 0;37m for lighter color
command_style=$reset_style'\[\033[1;29m\]' # bold black
fi
prompt_style=$reset_style
# Prompt variable:
PS1="$status_style"'$fill $(date +"%m/%d/%y ")\t\n'"$prompt_style"'${debian_chroot:+($debian_chroot)}\u@\h:\w\$'"$command_style "
# Reset color for command output
# (this one is invoked every time before a command is executed):
trap 'echo -ne "\033[00m"' DEBUG
function prompt_command {
# create a $fill of all screen width minus the time string and a space:
let fillsize=${COLUMNS}-18
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
Run Code Online (Sandbox Code Playgroud)
编辑(第 2 部分):现在.bash_ps1
在您的/root
文件夹中创建一个链接
sudo -s
cd /root
ln -s /home/<username>/.bash_ps1
Run Code Online (Sandbox Code Playgroud)
您可以更改上述任何代码以满足您的需要。这是我在工作中实际使用的一个,以便我知道我是否以root
用户身份输入可能存在潜在危险的命令。另外,时间戳显示在您键入的每一行上方,如果您回滚查看何时键入该命令,会更容易一些。
希望这会有所帮助!