Skip to content
TUWLAB.com
모든 게시물에 대하여 '링크'
방식의 퍼가기만 허용합니다.
한양대학교 전자통신컴퓨터공학부
바라미
  • 690
  • 2573354
DNS Powered by DNSEver.com
Linux

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

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

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


서비스 선택
이용중인 SNS 버튼을 클릭하여 로그인 해주세요.
SNS 계정을 통해 로그인하면 회원가입 없이 댓글을 남길 수 있습니다.
댓글
?
Powered by SocialXE

List of Articles
번호 분류 제목 글쓴이 최근 수정일 조회 수
129 OrCAD [OrCAD 16.3] Capture 부품 이동하며 자동 연결 옵션 설정하기 file TUW 2021.12.28 12339
128 일반 PSpice 시뮬레이션 결과창에서 Search Command 사용하기 file TUW 2017.06.02 31893
127 PSpice PSpice에서 Global Parameter Sweep을 활용하여 가변저항 시뮬레이션하기 file TUW 2021.12.28 45699
126 PSpice PSpice Performance Analysis file TUW 2021.12.28 11023
125 PSpice PSpice MOSFET 시뮬레이션 - MbreakN/P 사용방법 file TUW 2017.06.02 46726
124 Apache robots.txt를 활용하여 검색엔진 로봇 인덱싱 제한하기 TUW 2014.04.23 9462
123 Linux [Ubuntu] 서버 복구 : 설치부터 세팅까지 Quick Guide TUW 2013.07.08 15075
122 Apache Apache에서 서브 도메인 및 가상 호스트 설정하기 file TUW 2017.06.02 37988
121 일반 Eclipse에 C/C++ 개발환경 구축하기 file TUW 2017.06.02 9911
120 일반 형광등기구 안정기 교환 file TUW 2021.12.28 11960
119 일반 Windows 7에서 보호된 노트북 복구파티션 삭제하기 file TUW 2017.06.02 44051
118 Apache Apache에서 디렉토리별 php.ini 다르게 적용하기 (php_value, php_flag) TUW 2014.04.23 14472
117 Linux Linux 시스템 종료 명령어 - shutdown과 halt TUW 2014.04.23 24472
116 XE XE 게시판 '스킨 관리' 탭에 저장 버튼 및 목차 추가하기 file TUW 2021.12.28 11635
115 Linux [vsFTP] 생성 파일 기본 권한 설정하기 file TUW 2017.06.02 17803
114 일반 [포토샵] 사진 가장자리 투명하게 처리하기 file TUW 2017.06.02 42296
목록
Board Pagination Prev 1 2 3 4 5 6 7 8 ... 13 Next
/ 13

Powered by Xpress Engine / Designed by Sketchbook

sketchbook5, 스케치북5

sketchbook5, 스케치북5