Color Bash Prompt (Español)

From ArchWiki
Revision as of 04:46, 31 July 2008 by Starchox (Talk | contribs) (Colorear Indicador Bash (Español): iniciado)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Tango-preferences-desktop-locale.pngThis article or section needs to be translated.Tango-preferences-desktop-locale.png

Notes: please use the first argument of the template to provide more detailed indications. (Discuss in Talk:Color Bash Prompt (Español)#)
Template:I18n links start

Template:I18n entry Template:I18n entry Template:I18n entry Template:I18n links end

Resumén

Existe una gran variedad de posibilidades para mejorar el indicador de bash y personalizandolo ayudara a ser más productivo en la linea de comandos. Se puede agregar información adicional al indicador, o simplemente colorearlo para hacer el indicador más atractivo.

Indicadores Basicos

Las siguientes configuraciones son útiles para distinguit el indicador de root de otros usuarios sin privilegios:

Verde para usuarios normales:

export PS1='\[\e[0;32m\]\u@\h \W]\$ '

Coloca la variable PS1 anterior en el archivo ~/.bashrc y exportalo.

Rojo para el usuario root:

export PS1='\[\e[0;31m\]\u@\h \W]\$ '

Coloca la variable PS1 anterior en el archivo ~/.bashrc y exportalo.

Distinguir Indicadores de root y otros usuarios

Utilizar el archivo ~/.bashrc; uno del usuario root, y uno para usuarios normales:

vim ~/.bashrc

Comentar el PS1 inicial:

#PS1='[\u@\h \W]\$ '

Utilizar el siguiente indicador como usuario normal:

PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\]\[\e[1;37m\] '

Este indicador tiene las caracteristicas de que el nombre de usuario esta en verde, el directorio de trabajo en azul claro, un indicador $ en verde claro y la escritura de texto en blanco.

Editar el indicador del usuario root:

sudo vim /root/.bashrc

Comentar el PS1 inicial:

#PS1='[\u@\h \W]\$ '

Utilizar el siguiente indicador como usuario root:

PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$\[\e[m\]\[\e[0;32m\] '

Este indicador tiene las caracteristicas de que el nombre 'root' esta en rojo, el directorio de trabajo en azul claro, un indicador # en rojo y la escritura de texto en un horrible, tipo matrix, verde. ;)

Esta es la lista de algunos códigos de color para bash:

Negro       0;30     Gris Obscuro  1;30
Azul        0;34     Azul Claro    1;34
Verde       0;32     Verde Claro   1;32
Cyan        0;36     Cyan Claro    1;36
Rojo        0;31     Rojo Claro    1;31
Purpura     0;35     Fiuscha       1;35
Café        0;33     Amarillo      1;33
Gris Claro  0;37     Blanco        1;37

Reemplazar el digito 0 con 1 para obtener la versión del color claro, experimenta a tu gusto, y revisa el extracto de las páginas del manual de bash a continuación para además personalizar los carácteres especiales de escape.

Consejo:

\[     comienza un secuencia de carácteres no imprimibles
\]     termina un secuencia de carácteres no imprimibles

Customize your Bash prompt further

  • Edit your ~/.bashrc by commenting out the default Arch prompt:
# PS1='[\u@\h \W]\$ '
  • Add the following entries to your ~/.bashrc
BLUE=`tput setf 1`
GREEN=`tput setf 2`
CYAN=`tput setf 3`
RED=`tput setf 4`
MAGENTA=`tput setf 5`
YELLOW=`tput setf 6`
WHITE=`tput setf 7`
PS1='\[$GREEN\]\u@\h \[$BLUE\]\w/\[$GREEN\] \$\[$WHITE\] '

The \[ and \] are necessary to not get line-wrapping problems on the terminal.

Then do:

source ~/.bashrc

You may wish to edit your /root/.bashrc with a similar set of entries, perhaps with RED to indicate \u.


the various \x's (ripped from bash manpage):

     Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters that are decoded as follows:
            \a     an ASCII bell character (07)
            \d     the date in "Weekday Month Date" format (e.g., "Tue May 26")
            \D{format}
                   the format is passed to strftime(3) and the result is inserted into the  prompt  string;  an  empty  format
                   results in a locale-specific time representation.  The braces are required
            \e     an ASCII escape character (033)
            \h     the hostname up to the first `.'
            \H     the hostname
            \j     the number of jobs currently managed by the shell
            \l     the basename of the shell's terminal device name
            \n     newline
            \r     carriage return
            \s     the name of the shell, the basename of $0 (the portion following the final slash)
            \t     the current time in 24-hour HH:MM:SS format
            \T     the current time in 12-hour HH:MM:SS format
            \@     the current time in 12-hour am/pm format
            \A     the current time in 24-hour HH:MM format
            \u     the username of the current user
            \v     the version of bash (e.g., 2.00)
            \V     the release of bash, version + patch level (e.g., 2.00.0)
            \w     the current working directory, with $HOME abbreviated with a tilde
            \W     the basename of the current working directory, with $HOME abbreviated with a tilde
            \!     the history number of this command
            \#     the command number of this command
            \$     if the effective UID is 0, a #, otherwise a $
            \nnn   the character corresponding to the octal number nnn
            \\     a backslash
            \[     begin  a sequence of non-printing characters, which could be used to embed a terminal control sequence into
                   the prompt
            \]     end a sequence of non-printing characters
            
     The command number and the history number are usually different: the history number of a command is its position  in  the
     history  list, which may include commands restored from the history file (see HISTORY below), while the command number is
     the position in the sequence of commands executed during the current shell session.  After the string is decoded,  it  is
     expanded  via parameter expansion, command substitution, arithmetic expansion, and quote removal, subject to the value of
     the promptvars shell option (see the description of the shopt command under SHELL BUILTIN COMMANDS below).

Advanced Prompts

Wolfman's

After reading through most of the Bash Prompt Howto, I developed a color bash prompt that displays the last 25 characters of the current working directory. This prompt should work well on terminals with a black background. The following code goes in your home directory's .bashrc file.

  • Comment out Arch's default prompt.
# PS1='[\u@\h \W]\$ '
  • Next add the bash_prompt_command function. If you have a couple directories with long names or start entering a lot of subdirectories, this function will keep the command prompt from wrapping around the screen by displaying at most the last pwdmaxlen characters from the PWD. This code was taken from the Bash Prompt Howto's section on Controlling the Size and Appearance of $PWD and modified to replace the user's home directory with a tilde.
##################################################
# Fancy PWD display function
##################################################
# The home directory (HOME) is replaced with a ~
# The last pwdmaxlen characters of the PWD are displayed
# Leading partial directory names are striped off
# /home/me/stuff          -> ~/stuff               if USER=me
# /usr/share/big_dir_name -> ../share/big_dir_name if pwdmaxlen=20
##################################################
bash_prompt_command() {
    # How many characters of the $PWD should be kept
    local pwdmaxlen=25
    # Indicate that there has been dir truncation
    local trunc_symbol=".."
    local dir=${PWD##*/}
    pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
    NEW_PWD=${PWD/#$HOME/\~}
    local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
    if [ ${pwdoffset} -gt "0" ]
    then
        NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
        NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
    fi
}
  • This code generates the command prompt. There's not much to this. A bunch of colors are defined. The user's color for the username, hostname, and prompt ($ or #) is set to cyan, and if the user is root (root's UID is always 0), set the color to red. The command prompt is set to a colored version of Arch's default with the NEW_PWD from the last function.
  • Also, make sure that your color variables are enclosed in double and not single quote marks. Using single quote marks seems to give bash problems with line wrapping correctly.
bash_prompt() {
    case $TERM in
     xterm*|rxvt*)
         local TITLEBAR='\[\033]0;\u:${NEW_PWD}\007\]'
          ;;
     *)
         local TITLEBAR=""
          ;;
    esac
    local NONE="\[\033[0m\]"    # unsets color to term's fg color
    
    # regular colors
    local K="\[\033[0;30m\]"    # black
    local R="\[\033[0;31m\]"    # red
    local G="\[\033[0;32m\]"    # green
    local Y="\[\033[0;33m\]"    # yellow
    local B="\[\033[0;34m\]"    # blue
    local M="\[\033[0;35m\]"    # magenta
    local C="\[\033[0;36m\]"    # cyan
    local W="\[\033[0;37m\]"    # white
    
    # emphasized (bolded) colors
    local EMK="\[\033[1;30m\]"
    local EMR="\[\033[1;31m\]"
    local EMG="\[\033[1;32m\]"
    local EMY="\[\033[1;33m\]"
    local EMB="\[\033[1;34m\]"
    local EMM="\[\033[1;35m\]"
    local EMC="\[\033[1;36m\]"
    local EMW="\[\033[1;37m\]"
    
    # background colors
    local BGK="\[\033[40m\]"
    local BGR="\[\033[41m\]"
    local BGG="\[\033[42m\]"
    local BGY="\[\033[43m\]"
    local BGB="\[\033[44m\]"
    local BGM="\[\033[45m\]"
    local BGC="\[\033[46m\]"
    local BGW="\[\033[47m\]"
    
    local UC=$W                 # user's color
    [ $UID -eq "0" ] && UC=$R   # root's color
    
    PS1="$TITLEBAR ${EMK}[${UC}\u${EMK}@${UC}\h ${EMB}\${NEW_PWD}${EMK}]${UC}\\$ ${NONE}"
    # without colors: PS1="[\u@\h \${NEW_PWD}]\\$ "
    # extra backslash in front of \$ to make bash colorize the prompt
}
  • Finally, append this code. This ensures that the NEW_PWD variable will be updated when you cd somewhere else, and it sets the PS1 variable, which contains the command prompt.
PROMPT_COMMAND=bash_prompt_command
bash_prompt
unset bash_prompt
  • If you want to play around with the colors of this prompt, open your .bashrc file in a text editor. When you want to see what the new prompt looks like, enter the following from your home directory, and the prompt will immediately change.
$ source ~/.bashrc

External Resources