Linux

[Ubuntu] Bashrc Shell Prompt 커스터마이징 (.bashrc PS1)

Posted 2013. 07. 14 Updated 2014. 04. 24 Views 22796 Replies 0
?

단축키

Prev이전 문서

Next다음 문서

ESC닫기

크게 작게 위로 아래로 댓글로 가기 인쇄

Ubuntu의 터미널이나 SSH 접속시 표시되는 Shell Prompt의 모양을 사용자 입맛대로 바꿀 수 있습니다. 단순한 색상 변경은 물론이고, 표시되는 정보까지 바꿀 수 있습니다.

Ubuntu를 설치하고 최초에는 프롬포트의 형태가 다음과 같은 모양입니다.

user@my.server.com:/home/user/blahblah/Andromeda/$ 

이렇게 표시되는 프롬포트을 바꿀 수 있다는건 예전부터 알고 있었지만, 그간 딱히 불편함을 느꼈던 것은 아니었으므로 그냥 사용해 왔습니다.

헌데, 근래에 들어서 작업하는 디렉토리 깊이가 좀 깊어졌는데, 입력칸이 저~기 오른쪽 끝에 가 있거나 심지어 줄바꿈이 되는 일도 심심치 않게 일어났습니다.. =.=;;

결국 구글링을 통해 이걸 바꾸는 방법을 찾아내서 곧바로 적용하였습니다. 커스터마이징한 프롬포트의 모양은 대략 다음과 같습니다.

 
 [03:09:15]
! /home
 user@tuwlab.com$

우선, Shell이 세 줄로 표시되게 변경하였습니다. 첫 번째 줄은 이전 Shell과 구분을 명확하게 하기 위해 공란을 두었고, 다음 줄에는 현재 시각과 디렉토리 경로가 표시되도록 하였습니다. 마지막 번째 줄은 사용자명과 서버 이름만 표시합니다.

역상 모양의 빨간 느낌표는 직전에 실행한 명령이 올바르게 종료되지 못했을 경우에만 나타납니다. 간혹 오류메시지를 출력하지 않는 프로그램이 올바르게 종료되지 않았을 경우 이것을 감지하기 위한 목적입니다.

프롬포트의 색깔이나 모양을 수정하려면 ColorGCC처럼 별도의 패키지를 설치해야 하는 줄 알았는데 그게 아니었습니다. 홈 디렉토리에 있는 .bashrc 파일만 적절히 수정해 주면 프롬포트를 이렇게 컬러풀하고 유용하게 바꿀 수 있습니다.


우선 .bashrc 파일을 열고 색상 표시를 활성화하기 위해 다음 줄의 주석을 해제합니다.

color_prompt=yes

조금 더 아래로 내려가보면 다음과 같은 줄이 보입니다.

...
if [ "$color_prompt" = yes ]; then
...

이 줄 윗부분에 다음 내용을 복붙해 넣습니다. Style 관련 Escape 구문들이 상당히 지저분하기 때문이 이렇게 매크로 상수로 지정해 놓고 쓰면 편리합니다.

...
# Console Style Constants
RST="\[\e[0m\]"           # Reset Styles
BOLD="\[\e[1m\]"          # Bold
UL="\[\e[4m\]"            # Underline
HL="\[\e[7m\]"            # Highlight (inverse)
FG_BLACK="\[\e[90m\]"     # Foreground black
FG_RED="\[\e[91m\]"       # Foreground red
FG_GREEN="\[\e[92m\]"     # Foreground green
FG_YELLOW="\[\e[93m\]"    # Foreground yellow
FG_BLUE="\[\e[94m\]"      # Foreground blue
FG_MAGENTA="\[\e[95m\]"   # Foreground magenta
FG_CYAN="\[\e[96m\]"      # Foreground cyan
FG_WHITE="\[\e[97m\]"     # Foreground white
BG_BLACK="\[\e[100m\]"    # Background black
BG_RED="\[\e[101m\]"      # Background red
BG_GREEN="\[\e[102m\]"    # Background green
BG_YELLOW="\[\e[103m\]"   # Background yellow
BG_BLUE="\[\e[104m\]"     # Background blue
BG_MAGENTA="\[\e[105m\]"  # Background magenta
BG_CYAN="\[\e[106m\]"     # Background cyan
BG_WHITE="\[\e[107m\]"    # Background white

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
...

* 각 색상의 Intensity 옵션으로 Normal Mode와 Bright Mode를 지정할 수 있는데, 여기서는 모두 Bright 모드를 사용했습니다. Normal Mode에 비해 Bright Mode는 색이 좀 더 밝게 표시됩니다. Normal Mode 색상을 사용하고자 할 때는 다음 링크를 참조하여 숫자를 바꿔주도록 합니다.

▶ ANSI Esapce Code : http://en.wikipedia.org/wiki/ANSI_escape_code

이제 저 아래에 있는 PS1 상수를 적절하게 수정하면 프롬포트의 모양을 지정해 줄 수 있습니다. 우선, 사용 가능한 Escape 문자들은 다음과 같다.

  • \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

( 참조 : http://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html )

위에서 정의한 매크로 상수와 Escape 문자들을 조합하여 PS1 변수를 재정의 해 주도록 합니다.

예를 들어, 지금 제가 사용하고 있는 PS1 변수는 다음과 같습니다. 지저분한 Style 관련 Escape 구문들을 상수로 치환해서 작성했기 때문에 어렵지 않게 문법을 이해할 수 있을 것입니다.

    PS1="\n${FG_MAGENTA}[\t]${RST}\`if [ \$? != 0 ]; then echo ' ${FG_RED}${BOLD}${HL}!${RST}'; fi\` ${FG_YELLOW}\\
w${RST}\n${debian_chroot:+($debian_chroot)}${FG_GREEN}${BOLD}\u${RST}${FG_WHITE}@${RST}${FG_CYAN}\h${RST}\$ "

수정을 완료한 뒤 다음 명령어를 쳐서 .bashrc를 Reload해 줍니다.

. ~/.bashrc