Bash 或 Z shell 终端提示带有时间和日期

Pur*_*rry 3 linux bash zsh ps1

我正在运行 Bash 和 Z shell(zsh可执行文件)作为我的终端环境。

\n

我的主要目标是我想在所有提示中添加时间戳......

\n

类似于:PS1_DATE="\\D{%Y-%m-%d %H:%M:%S}"

\n

这是来自 .bashrc 的提示

\n

这是来自 .zshrc 的提示

\n

我也希望我的提示看起来相同。如果我的两个提示符看起来像我的 Z shell 提示符(我喜欢这些颜色),我会喜欢它。

\n

目前,\xe2\x80\x99 中的任何一个看起来都是我想要的方式,这真是一个奇迹,因为我不知道自己在做什么,而且因为我弗兰肯斯坦修改了我的.bashrc.zshrc文件。对于任何有经验的人来说,它们可能看起来都很痛苦。

\n

据我所知,我在两个rc文件中都使用了.dir_colors文件,这会覆盖颜色设置,但它们应该仅适用于 \xe2\x80\x9cLS\xe2\x80\x9d,尽管我可能是错的。

\n

当前.bashrc文件:

\n
#\n# ~/.bashrc\n#\n\n[[ $- != *i* ]] && return\n\ncolors() {\n    local fgc bgc vals seq0\n\n    printf "Color escapes are %s\\n" \'\\e[${value};...;${value}m\'\n    printf "Values 30..37 are \\e[33mforeground colors\\e[m\\n"\n    printf "Values 40..47 are \\e[43mbackground colors\\e[m\\n"\n    printf "Value  1 gives a  \\e[1mbold-faced look\\e[m\\n\\n"\n\n    # foreground colors\n    for fgc in {30..37}; do\n        # background colors\n        for bgc in {40..47}; do\n            fgc=${fgc#37} # white\n            bgc=${bgc#40} # black\n\n            vals="${fgc:+$fgc;}${bgc}"\n            vals=${vals%%;}\n\n            seq0="${vals:+\\e[${vals}m}"\n            printf "  %-9s" "${seq0:-(default)}"\n            printf " ${seq0}TEXT\\e[m"\n            printf " \\e[${vals:+${vals+$vals;}}1mBOLD\\e[m"\n        done\n        echo; echo\n    done\n}\n\n[ -r /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion\n\n# Change the window title of X terminals\ncase ${TERM} in\n    xterm*|rxvt*|Eterm*|aterm|kterm|gnome*|interix|konsole*)\n        PROMPT_COMMAND=\'echo -ne "\\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/\\~}\\007"\'\n        ;;\n    screen*)\n        PROMPT_COMMAND=\'echo -ne "\\033_${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/\\~}\\033\\\\"\'\n        ;;\nesac\n\nuse_color=true\n\n# Set colorful PS1 only on colorful terminals.\n# dircolors --print-database uses its own built-in database\n# instead of using /etc/DIR_COLORS.  Try to use the external file\n# first to take advantage of user additions.  Use internal bash\n# globbing instead of external grep binary.\nsafe_term=${TERM//[^[:alnum:]]/?}   # sanitize TERM\nmatch_lhs=""\n[[ -f ~/.dir_colors   ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"\n[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"\n[[ -z ${match_lhs}    ]] \\\n    && type -P dircolors >/dev/null \\\n    && match_lhs=$(dircolors --print-database)\n[[ $\'\\n\'${match_lhs} == *$\'\\n\'"TERM "${safe_term}* ]] && use_color=true\n\nif ${use_color} ; then\n    # Enable colors for ls, etc.  Prefer ~/.dir_colors #64489\n    if type -P dircolors >/dev/null ; then\n        if [[ -f ~/.dir_colors ]] ; then\n            eval $(dircolors -b ~/.dir_colors)\n        elif [[ -f /etc/DIR_COLORS ]] ; then\n            eval $(dircolors -b /etc/DIR_COLORS)\n        fi\n    fi\n\n    if [[ ${EUID} == 0 ]] ; then\n        PS1=\'\\[\\033[01;31m\\][\\h\\[\\033[01;36m\\] \\W\\[\\033[01;31m\\]]\\$\\[\\033[00m\\] \'\n    else\n        PS1=\'\\[\\033[01;32m\\][\\u@\\h\\[\\033[01;37m\\] \\W\\[\\033[01;32m\\]]\\$\\[\\033[00m\\] \'\n    fi\n\n    alias ls=\'ls --color=auto\'\n    alias grep=\'grep --colour=auto\'\n    alias egrep=\'egrep --colour=auto\'\n    alias fgrep=\'fgrep --colour=auto\'\nelse\n    if [[ ${EUID} == 0 ]] ; then\n        # show root@ when we don\'t have colors\n        PS1=\'\\u@\\h \\W \\$ \'\n    else\n        PS1=\'\\u@\\h \\w \\$ \'\n    fi\nfi\n\nunset use_color safe_term match_lhs sh\n\nalias cp="cp -i"                          # confirm before overwriting something\nalias df=\'df -h\'                          # human-readable sizes\nalias free=\'free -m\'                      # show sizes in MB\nalias np=\'nano -w PKGBUILD\'\nalias more=less\n\nxhost +local:root > /dev/null 2>&1\n\ncomplete -cf sudo\n\n# Bash won\'t get SIGWINCH if another process is in the foreground.\n# Enable checkwinsize so that bash will check the terminal size when\n# it regains control.  #65623\n# http://cnswww.cns.cwru.edu/~chet/bash/FAQ (E11)\nshopt -s checkwinsize\n\nshopt -s expand_aliases\n\n# export QT_SELECT=4\n\n# Enable history appending instead of overwriting.  #139609\nshopt -s histappend\n\n#\n# # ex - archive extractor\n# # usage: ex <file>\nex ()\n{\n  if [ -f $1 ] ; then\n    case $1 in\n      *.tar.bz2)   tar xjf $1   ;;\n      *.tar.gz)    tar xzf $1   ;;\n      *.bz2)       bunzip2 $1   ;;\n      *.rar)       unrar x $1     ;;\n      *.gz)        gunzip $1    ;;\n      *.tar)       tar xf $1    ;;\n      *.tbz2)      tar xjf $1   ;;\n      *.tgz)       tar xzf $1   ;;\n      *.zip)       unzip $1     ;;\n      *.Z)         uncompress $1;;\n      *.7z)        7z x $1      ;;\n      *)           echo "\'$1\' cannot be extracted via ex()" ;;\n    esac\n  else\n    echo "\'$1\' is not a valid file"\n  fi\n}\n
Run Code Online (Sandbox Code Playgroud)\n

当前.zshrc文件:

\n
# config for the Zoomer Shell\n\n# Enable colors and change prompt:\nautoload -U colors && colors\nPS1="%B%{$fg[red]%}[%{$fg[yellow]%}%n%{$fg[green]%}@%{$fg[blue]%}%M %{$fg[magenta]%}%~%{$fg[red]%}]%{$reset_color%}$%b "\n\n# History in cache directory:\nHISTSIZE=10000\nSAVEHIST=10000\nHISTFILE=~/.cache/zsh/history\n\nsafe_term=${TERM//[^[:alnum:]]/?}   # sanitize TERM\nmatch_lhs=""\n[[ -f ~/.dir_colors   ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"\n[[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"\n[[ -z ${match_lhs}    ]] \\\n    && type dircolors >/dev/null \\\n    && match_lhs=$(dircolors --print-database)\n[[ $\'\\n\'${match_lhs} == *$\'\\n\'"TERM "${safe_term}* ]] && use_color=true\n\nif ${use_color} ; then\n    # Enable colors for ls, etc.  Prefer ~/.dir_colors #64489\n    if type dircolors >/dev/null ; then\n        if [[ -f ~/.dir_colors ]] ; then\n            eval $(dircolors -b ~/.dir_colors)\n        elif [[ -f /etc/DIR_COLORS ]] ; then\n            eval $(dircolors -b /etc/DIR_COLORS)\n        fi\n    fi\n\n    alias ls=\'ls --color=auto\'\n    alias grep=\'grep --colour=auto\'\n    alias egrep=\'egrep --colour=auto\'\n    alias fgrep=\'fgrep --colour=auto\'\nelse\n    if [[ ${EUID} == 0 ]] ; then\n        # show root@ when we don\'t have colors\n        PS1=\'\\u@\\h \\W \\$ \'\n    else\n        PS1=\'\\u@\\h \\w \\$ \'\n    fi\nfi\n\nunset use_color safe_term match_lhs sh\n\nalias cp="cp -i"                          # confirm before overwriting something\nalias df=\'df -h\'                          # human-readable sizes\nalias free=\'free -m\'                      # show sizes in MB\nalias np=\'nano -w PKGBUILD\'\nalias more=less\n\nxhost +local:root > /dev/null 2>&1\n\n\n# Basic auto/tab complete:\nautoload -U compinit\nzstyle \':completion:*\' menu select\nzmodload zsh/complist\ncompinit\n_comp_options+=(globdots)       # Include hidden files.\n\n# vi mode\nbindkey -v\nexport KEYTIMEOUT=1\n\n# Use vim keys in tab complete menu:\nbindkey -M menuselect \'h\' vi-backward-char\nbindkey -M menuselect \'k\' vi-up-line-or-history\nbindkey -M menuselect \'l\' vi-forward-char\nbindkey -M menuselect \'j\' vi-down-line-or-history\nbindkey -v \'^?\' backward-delete-char\n\n# Change cursor shape for different vi modes.\nfunction zle-keymap-select {\n  if [[ ${KEYMAP} == vicmd ]] ||\n     [[ $1 = \'block\' ]]; then\n    echo -ne \'\\e[1 q\'\n  elif [[ ${KEYMAP} == main ]] ||\n       [[ ${KEYMAP} == viins ]] ||\n       [[ ${KEYMAP} = \'\' ]] ||\n       [[ $1 = \'beam\' ]]; then\n    echo -ne \'\\e[5 q\'\n  fi\n}\nzle -N zle-keymap-select\nzle-line-init() {\n    zle -K viins # initiate `vi insert` as keymap (can be removed if `bindkey -V` has been set elsewhere)\n    echo -ne "\\e[5 q"\n}\nzle -N zle-line-init\necho -ne \'\\e[5 q\' # Use beam shape cursor on startup.\npreexec() { echo -ne \'\\e[5 q\' ;} # Use beam shape cursor for each new prompt.\n\n# Edit line in vim with ctrl-e:\nautoload edit-command-line; zle -N edit-command-line\nbindkey \'^e\' edit-command-line\n\n# Load aliases and shortcuts if existent.\n[ -f "$HOME/.config/shortcutrc" ] && source "$HOME/.config/shortcutrc"\n[ -f "$HOME/.config/aliasrc" ] && source "$HOME/.config/aliasrc"\n\n# Load zsh-syntax-highlighting; should be last.\nsource /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh 2>/dev/null\n\nsource ~/path/to/fsh/fast-syntax-highlighting.plugin.zsh\n\n
Run Code Online (Sandbox Code Playgroud)\n

当前.dir_colors文件:

\n
# Configuration file for dircolors, a utility to help you set the\n# LS_COLORS environment variable used by GNU ls with the --color option.\n\n# Copyright (C) 1996-2014 Free Software Foundation, Inc.\n# Copying and distribution of this file, with or without modification,\n# are permitted provided the copyright notice and this notice are preserved.\n\n# The keywords COLOR, OPTIONS, and EIGHTBIT (honored by the\n# slackware version of dircolors) are recognized but ignored.\n\n# You can copy this file to .dir_colors in your $HOME directory to override\n# the system defaults.\n\n# Below, there should be one TERM entry for each termtype that is colorizable\nTERM Eterm\nTERM ansi\nTERM color-xterm\nTERM con132x25\nTERM con132x30\nTERM con132x43\nTERM con132x60\nTERM con80x25\nTERM con80x28\nTERM con80x30\nTERM con80x43\nTERM con80x50\nTERM con80x60\nTERM cons25\nTERM console\nTERM cygwin\nTERM dtterm\nTERM eterm-color\nTERM gnome\nTERM gnome-256color\nTERM hurd\nTERM jfbterm\nTERM konsole\nTERM kterm\nTERM linux\nTERM linux-c\nTERM mach-color\nTERM mach-gnu-color\nTERM mlterm\nTERM putty\nTERM putty-256color\nTERM rxvt\nTERM rxvt-256color\nTERM rxvt-cygwin\nTERM rxvt-cygwin-native\nTERM rxvt-unicode\nTERM rxvt-unicode-256color\nTERM rxvt-unicode256\nTERM screen\nTERM screen-256color\nTERM screen-256color-bce\nTERM screen-bce\nTERM screen-w\nTERM screen.Eterm\nTERM screen.rxvt\nTERM screen.linux\nTERM st\nTERM st-256color\nTERM terminator\nTERM vt100\nTERM xterm\nTERM xterm-16color\nTERM xterm-256color\nTERM xterm-88color\nTERM xterm-color\nTERM xterm-debian\n\n# Below are the color init strings for the basic file types. A color init\n# string consists of one or more of the following numeric codes:\n# Attribute codes:\n# 00=none 01=bold 04=underscore 05=blink 07=reverse 08=concealed\n# Text color codes:\n# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white\n# Background color codes:\n# 40=black 41=red 42=green 43=yellow 44=blue 45=magenta 46=cyan 47=white\n#NORMAL 00  # no color code at all\n#FILE 00    # regular file: use no color at all\nRESET 0     # reset to "normal" color\nDIR 01;34   # directory\nLINK 01;36  # symbolic link.  (If you set this to \'target\' instead of a\n                # numerical value, the color is as for the file pointed to.)\nMULTIHARDLINK 00    # regular file with more than one link\nFIFO 40;33  # pipe\nSOCK 01;35  # socket\nDOOR 01;35  # door\nBLK 40;33;01    # block device driver\nCHR 40;33;01    # character device driver\nORPHAN 01;05;37;41  # orphaned syminks\nMISSING 01;05;37;41 # ... and the files they point to\nSETUID 37;41    # file that is setuid (u+s)\nSETGID 30;43    # file that is setgid (g+s)\nCAPABILITY 30;41    # file with capability\nSTICKY_OTHER_WRITABLE 30;42 # dir that is sticky and other-writable (+t,o+w)\nOTHER_WRITABLE 34;42 # dir that is other-writable (o+w) and not sticky\nSTICKY 37;44    # dir with the sticky bit set (+t) and not other-writable\n\n# This is for files with execute permission:\nEXEC 01;32\n\n# List any file extensions like \'.gz\' or \'.tar\' that you would like ls\n# to colorize below. Put the extension, a space, and the color init string.\n# (and any comments you want to add after a \'#\')\n\n# If you use DOS-style suffixes, you may want to uncomment the following:\n#.cmd 01;32 # executables (bright green)\n#.exe 01;32\n#.com 01;32\n#.btm 01;32\n#.bat 01;32\n# Or if you want to colorize scripts even if they do not have the\n# executable bit actually set.\n#.sh  01;32\n#.csh 01;32\n\n # archives or compressed (bright red)\n.tar 01;31\n.tgz 01;31\n.arc 01;31\n.arj 01;31\n.taz 01;31\n.lha 01;31\n.lz4 01;31\n.lzh 01;31\n.lzma 01;31\n.tlz 01;31\n.txz 01;31\n.tzo 01;31\n.t7z 01;31\n.zip 01;31\n.z   01;31\n.Z   01;31\n.dz  01;31\n.gz  01;31\n.lrz 01;31\n.lz  01;31\n.lzo 01;31\n.xz  01;31\n.bz2 01;31\n.bz  01;31\n.tbz 01;31\n.tbz2 01;31\n.tz  01;31\n.deb 01;31\n.rpm 01;31\n.jar 01;31\n.war 01;31\n.ear 01;31\n.sar 01;31\n.rar 01;31\n.alz 01;31\n.ace 01;31\n.zoo 01;31\n.cpio 01;31\n.7z  01;31\n.rz  01;31\n.cab 01;31\n\n# image formats\n.jpg 01;35\n.jpeg 01;35\n.gif 01;35\n.bmp 01;35\n.pbm 01;35\n.pgm 01;35\n.ppm 01;35\n.tga 01;35\n.xbm 01;35\n.xpm 01;35\n.tif 01;35\n.tiff 01;35\n.png 01;35\n.svg 01;35\n.svgz 01;35\n.mng 01;35\n.pcx 01;35\n.mov 01;35\n.mpg 01;35\n.mpeg 01;35\n.m2v 01;35\n.mkv 01;35\n.webm 01;35\n.ogm 01;35\n.mp4 01;35\n.m4v 01;35\n.mp4v 01;35\n.vob 01;35\n.qt  01;35\n.nuv 01;35\n.wmv 01;35\n.asf 01;35\n.rm  01;35\n.rmvb 01;35\n.flc 01;35\n.avi 01;35\n.fli 01;35\n.flv 01;35\n.gl 01;35\n.dl 01;35\n.xcf 01;35\n.xwd 01;35\n.yuv 01;35\n.cgm 01;35\n.emf 01;35\n\n# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions\n.axv 01;35\n.anx 01;35\n.ogv 01;35\n.ogx 01;35\n\n# Document files\n.pdf 00;32\n.ps 00;32\n.txt 00;32\n.patch 00;32\n.diff 00;32\n.log 00;32\n.tex 00;32\n.doc 00;32\n\n# audio formats\n.aac 00;36\n.au 00;36\n.flac 00;36\n.m4a 00;36\n.mid 00;36\n.midi 00;36\n.mka 00;36\n.mp3 00;36\n.mpc 00;36\n.ogg 00;36\n.ra 00;36\n.wav 00;36\n\n# http://wiki.xiph.org/index.php/MIME_Types_and_File_Extensions\n.axa 00;36\n.oga 00;36\n.spx 00;36\n.xspf 00;36\n
Run Code Online (Sandbox Code Playgroud)\n

Pur*_*rry 7

我补充道:

在文件.bashrc中:

\D{%F} \t
Run Code Online (Sandbox Code Playgroud)

到字符串的前面PS1=。这给了我完整的格式日期和时间。

在文件.zshrc中

20%D %*
Run Code Online (Sandbox Code Playgroud)

到字符串的前面PS1=。%D 仅提供 yy-mm-dd 格式,因此我在前面添加了 20,以统一两个提示中的内容。我也只是通过尝试将 zsh 提示符中的颜色与 bash 提示符相匹配来反复尝试。最后我得到了我想要的结果:

试错进展

当前.bashrc PS1:

PS1="\D{%F} \t \[\033[01;31m\][\[\033[01;33m\]\u\[\033[01;32m\]@\[\033[01;34m\]\h\[\033[01;37m\] \W\[\033[01;31m\]]\[\033[01;32m\]$\[\033[0m\] "
Run Code Online (Sandbox Code Playgroud)

当前.zshrc PS1

PS1="20%D %*%B%{$fg[red]%}[%{$fg[yellow]%}%n%{$fg[green]%}@%{$fg[blue]%}%M %{$fg[magenta]%}%~%{$fg[red]%}]%{$reset_color%}$%b "
Run Code Online (Sandbox Code Playgroud)

另外,我的试验过程中,我遇到了一个问题,即我在 bash 提示符上遇到奇怪的换行行为,超过一定数量字符的文本会换行到同一行并模糊我的提示符。

通过正确转义所有颜色添加解决了这个问题......

例子:

[\033[01;31m]

当前 Bash 提示符:

带时间戳的彩色提示