【问题标题】:Maintainable approach for generating a machine-specific PS1 Prompt用于生成特定于机器的 PS1 提示的可维护方法
【发布时间】:2017-08-01 09:14:15
【问题描述】:

为了帮助自己记住我登录到不同的系统,快速而直观,我为 Bash PS1 环境变量中的 \h 字段使用不同的颜色。

我正在寻找一种可靠地生成PS1 的方法,该方法与静态主机标识符相关联;比如说,通过hostid 命令。

原来,我的PS1,改编自bashrcgenerator.com生成的东西,看起来像:

export PS1="\u@\[$(tput bold)\]\[$(tput sgr0)\]\[\033[38;5;35m\]\h\[$(tput sgr0)\]\[$(tput sgr0)\]\[\033[38;5;15m\]\[$(tput sgr0)\]:\[\033[38;5;245m\]\w\[$(tput sgr0)\]\[\033[38;5;15m\]\[$(tput sgr0)\]\\$ "

真是一团糟。

所以要开始任何进展,第一步是进行一些重构。这让我看到了以下脚本:

bold="$(tput bold)"
reset="$(tput sgr0)"
green="\e[38;5;35m"
gray="\e[38;5;245m"

directory='\w'
host='\h'
user='\u'

function colorize() {
    echo -n "${2}${1}${reset}"
}

export PS1="${user}@$(colorize $host $green):$(colorize $directory $gray)\\$ "

此时,您至少可以看到到底发生了什么。

现在,我需要编写如下函数:

get_repeatable_color_for_hostid() {
    # hash the $(hostid) into a valid color escape string
    # e.g. 16ab1d60 --> \e[38;5;35m
}

为此,我需要了解:

  • 例如字段部分xx;y;zzm 的含义是什么? \e[38;5;35m?
  • 如何进行从hostid 到该颜色转义序列的散列,s.t.颜色尽可能随机化

【问题讨论】:

    标签: bash terminal xterm ps1 terminal-emulator


    【解决方案1】:

    关于颜色这个页面帮助我了解了所有细节:http://misc.flogisoft.com/bash/tip_colors_and_formatting

    由于没有太多颜色可供选择,因此只需为每个主机分配一种颜色,如果您有更多主机,则根据重要性(开发、产品等)对主机进行分组每个组都有自己的颜色。

    还有这个想法是使用主机名的校验和生成颜色(从1到256):COLOR=$(($(hostname | cksum | cut -f1 -d" ")%256+1))

    【讨论】:

    猜你喜欢
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2010-12-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2012-08-21
    相关资源
    最近更新 更多