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

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

Posted 2013. 07. 14 Updated 2014. 04. 24 Views 22837 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
번호 분류 제목 글쓴이 최근 수정일 조회 수
81 OrCAD [OrCAD 16.3] Capture 부품 이동하며 자동 연결 옵션 설정하기 file TUW 2021.12.28 12358
80 OrCAD [OrCAD Capture] 회로도 PDF로 출력하기 - PDF Export 활용 file TUW 2021.12.28 17970
79 Security [SSL/HTTPS] Let's Encrypt 무료 SSL 인증서 발급/설치/관리 - certbot 사용법 file TUW 2021.12.28 33675
78 Security [SSL/HTTPS] StartSSL/StartCom 사태와 Let's Encrypt로의 이전 1 file TUW 2021.12.28 12088
77 일반 [TeraTerm] 명령줄 인수와 공개키 인증으로 간편하게 SSH 접속하기 TUW 2018.11.06 4570
76 Linux [Ubuntu] 파티션 관리 프로그램 - GParted file TUW 2021.12.28 22502
» Linux [Ubuntu] Bashrc Shell Prompt 커스터마이징 (.bashrc PS1) TUW 2014.04.24 22837
74 Linux [Ubuntu] SSH 초기 접속 속도 향상시키기 TUW 2014.04.23 13826
73 Linux [Ubuntu] Windows와 멀티부팅 환경에서 시간이 맞지 않는 현상 해결하기 TUW 2017.06.08 29640
72 Linux [Ubuntu] 데이터 및 DB(MySQL)를 백업 및 복원하는 명령어 TUW 2014.04.20 15543
71 Linux [Ubuntu] 디스크 마운트하기 TUW 2014.04.20 36566
70 Linux [Ubuntu] 디스크 용량 확인 명령어 TUW 2014.04.20 13226
69 Linux [Ubuntu] 서버 복구 : 설치부터 세팅까지 Quick Guide TUW 2013.07.08 15082
68 Linux [Ubuntu] 원격 Shell에서 로그인 사용자 디스플레이에 GUI 프로그램 실행하기 TUW 2016.03.06 10054
67 Linux [Ubuntu] 화면캡처 및 작업공간 전환 단축키 TUW 2014.04.20 24165
66 Linux [Vi/Vim] 단축키 모음 file TUW 2017.06.02 11556
목록
Board Pagination Prev 1 ... 5 6 7 8 9 10 11 ... 13 Next
/ 13

Powered by Xpress Engine / Designed by Sketchbook

sketchbook5, 스케치북5

sketchbook5, 스케치북5